def Run(self, args): client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() try: digest = get_digest.GetDigest(args.digest_algorithm, args.input_file) except EnvironmentError as e: raise exceptions.BadFileException( 'Failed to read input file [{0}]: {1}'.format( args.input_file, e)) req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsAsymmetricSignRequest( # pylint: disable=line-too-long name=flags.ParseCryptoKeyVersionName(args).RelativeName()) req.asymmetricSignRequest = messages.AsymmetricSignRequest( digest=digest) resp = (client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions .AsymmetricSign(req)) try: log.WriteToFileOrStdout(args.signature_file, resp.signature, overwrite=True, binary=True, private=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() version_ref = flags.ParseCryptoKeyVersionName(args) if not version_ref.Name(): raise exceptions.InvalidArgumentException( 'version', 'version id must be non-empty.') versions = client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions version = versions.Get( messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest( name=version_ref.RelativeName())) if (version.protectionLevel != messages.CryptoKeyVersion.ProtectionLevelValueValuesEnum.HSM): raise exceptions.ToolException( 'Certificate chains are only available for HSM key versions.') if (version.state == messages.CryptoKeyVersion.StateValueValuesEnum. PENDING_GENERATION): raise exceptions.ToolException( 'Certificate chains are unavailable until the version is generated.' ) try: log.WriteToFileOrStdout( args.output_file if args.output_file else '-', _GetCertificateChainPem(version.attestation.certChains, args.certificate_chain_type), overwrite=True, binary=False) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): req = self._CreateDecryptRequest(args) client = cloudkms_base.GetClientInstance() try: resp = client.projects_locations_keyRings_cryptoKeys.Decrypt(req) # Intercept INVALID_ARGUMENT errors related to checksum verification to # present a user-friendly message. All other errors are surfaced as-is. except apitools_exceptions.HttpBadRequestError as error: e2e_integrity.ProcessHttpBadRequestError(error) if self._PerformIntegrityVerification(args): self._VerifyResponseIntegrityFields(req, resp) try: if resp.plaintext is None: with files.FileWriter(args.plaintext_file): # to create an empty file pass log.Print('Decrypted file is empty') else: log.WriteToFileOrStdout(args.plaintext_file, resp.plaintext, binary=True, overwrite=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): try: ciphertext = console_io.ReadFromFileOrStdin( args.ciphertext_file, binary=True) except files.Error as e: raise exceptions.BadFileException( 'Failed to read ciphertext file [{0}]: {1}'.format( args.ciphertext_file, e)) client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() crypto_key_ref = flags.ParseCryptoKeyVersionName(args) req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsAsymmetricDecryptRequest( # pylint: disable=line-too-long name=crypto_key_ref.RelativeName()) req.asymmetricDecryptRequest = messages.AsymmetricDecryptRequest( ciphertext=ciphertext) resp = ( client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions. AsymmetricDecrypt(req)) try: log.WriteToFileOrStdout( args.plaintext_file, resp.plaintext or '', overwrite=True, binary=True, private=True) except files.Error as e: raise exceptions.BadFileException(e)
def SaveAgentToFile(response, args): dest = args.destination if not IsBucketUri(dest): props = response.additionalProperties agent_content = next(prop for prop in props if prop.key == 'agentContent') agent_content_bin = base64.b64decode(agent_content.value.string_value) log.WriteToFileOrStdout(dest, agent_content_bin, binary=True) if dest != '-': log.status.Print('Wrote agent to [{}].'.format(dest)) return response
def Run(self, args): if (args.ciphertext_file == '-' and args.additional_authenticated_data_file == '-'): raise exceptions.InvalidArgumentException( '--ciphertext-file', '--ciphertext-file and --additional-authenticated-data-file cannot ' 'both read from stdin.') try: # The Encrypt API has a limit of 64K; the output ciphertext files will be # slightly larger. Check proactively (but generously) to avoid attempting # to buffer and send obviously oversized files to KMS. ciphertext = self._ReadFileOrStdin( args.ciphertext_file, max_bytes=2 * 65536) except files.Error as e: raise exceptions.BadFileException( 'Failed to read ciphertext file [{0}]: {1}'.format( args.ciphertext_file, e)) aad = None if args.additional_authenticated_data_file: try: # The Encrypt API limits the AAD to 64KiB. aad = self._ReadFileOrStdin( args.additional_authenticated_data_file, max_bytes=65536) except files.Error as e: raise exceptions.BadFileException( 'Failed to read additional authenticated data file [{0}]: {1}'. format(args.additional_authenticated_data_file, e)) crypto_key_ref = flags.ParseCryptoKeyName(args) client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest( name=crypto_key_ref.RelativeName()) req.decryptRequest = messages.DecryptRequest( ciphertext=ciphertext, additionalAuthenticatedData=aad) resp = client.projects_locations_keyRings_cryptoKeys.Decrypt(req) try: if resp.plaintext is None: with files.FileWriter(args.plaintext_file): # to create an empty file pass log.Print('Decrypted file is empty') else: log.WriteToFileOrStdout( args.plaintext_file, resp.plaintext, binary=True, overwrite=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): resp = super(CreateALPHA, self).Run(args) if args.attestation_file and resp.primary.attestation is not None: try: log.WriteToFileOrStdout(args.attestation_file, encoding.MessageToJson( resp.primary.attestation), overwrite=True, binary=False, private=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): client, messages = util.GetClientAndMessages() response = client.projects_serviceAccounts.SignBlob( messages.IamProjectsServiceAccountsSignBlobRequest( name=iam_util.EmailToAccountResourceName(args.iam_account), signBlobRequest=messages.SignBlobRequest( bytesToSign=files.ReadBinaryFileContents(args.input)))) log.WriteToFileOrStdout( args.output, content=response.signature, binary=True) log.status.Print( 'signed blob [{0}] as [{1}] for [{2}] using key [{3}]'.format( args.input, args.output, args.iam_account, response.keyId))
def Run(self, args): response = self.iam_client.projects_serviceAccounts.SignJwt( self.messages.IamProjectsServiceAccountsSignJwtRequest( name=iam_util.EmailToAccountResourceName(args.iam_account), signJwtRequest=self.messages.SignJwtRequest( payload=self.ReadFile(args.input)))) log.WriteToFileOrStdout(args.output, content=response.signedJwt, binary=True) log.status.Print( 'signed jwt [{0}] as [{1}] for [{2}] using key [{3}]'.format( args.input, args.output, args.iam_account, response.keyId))
def Run(self, args): client, messages = util.GetClientAndMessages() response = client.projects_serviceAccounts.SignJwt( messages.IamProjectsServiceAccountsSignJwtRequest( name=iam_util.EmailToAccountResourceName(args.iam_account), signJwtRequest=messages.SignJwtRequest( payload=files.ReadFileContents(args.input,)))) log.WriteToFileOrStdout( args.output, content=response.signedJwt, binary=False, private=True) log.status.Print( 'signed jwt [{0}] as [{1}] for [{2}] using key [{3}]'.format( args.input, args.output, args.iam_account, response.keyId))
def Run(self, args): if (args.plaintext_file == '-' and args.additional_authenticated_data_file == '-'): raise exceptions.InvalidArgumentException( '--plaintext-file', '--plaintext-file and --additional-authenticated-data-file cannot ' 'both read from stdin.') try: # The Encrypt API limits the plaintext to 64KiB. plaintext = self._ReadFileOrStdin(args.plaintext_file, max_bytes=65536) except files.Error as e: raise exceptions.BadFileException( 'Failed to read plaintext file [{0}]: {1}'.format( args.plaintext_file, e)) aad = None if args.additional_authenticated_data_file: try: # The Encrypt API limits the AAD to 64KiB. aad = self._ReadFileOrStdin( args.additional_authenticated_data_file, max_bytes=65536) except files.Error as e: raise exceptions.BadFileException( 'Failed to read additional authenticated data file [{0}]: {1}' .format(args.additional_authenticated_data_file, e)) if args.version: crypto_key_ref = flags.ParseCryptoKeyVersionName(args) else: crypto_key_ref = flags.ParseCryptoKeyName(args) client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() req = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest( name=crypto_key_ref.RelativeName()) req.encryptRequest = messages.EncryptRequest( plaintext=plaintext, additionalAuthenticatedData=aad) resp = client.projects_locations_keyRings_cryptoKeys.Encrypt(req) try: log.WriteToFileOrStdout(args.ciphertext_file, resp.ciphertext, binary=True, overwrite=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): """Runs the get-public-cert command.""" with endpoint_util.GkemulticloudEndpointOverride( resource_args.ParseAzureClientResourceArg(args).locationsId, self.ReleaseTrack()): client_ref = resource_args.ParseAzureClientResourceArg(args) api_client = api_util.ClientsClient() client = api_client.Get(client_ref) cert = self._GetCert(client) log.WriteToFileOrStdout( args.output_file if args.output_file else '-', cert, overwrite=True, binary=False, private=True)
def _DescribeResponse(self, args, resp): if args.attestation_file and resp.primary.attestation: try: log.WriteToFileOrStdout(args.attestation_file, encoding.MessageToJson( resp.primary.attestation), overwrite=True, binary=False, private=True) except files.Error as e: raise exceptions.BadFileException(e) if resp.primary.attestation: # blank out the attestation in the response. resp.primary.attestation = None return resp
def Run(self, args): client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() version_ref = flags.ParseCryptoKeyVersionName(args) if not version_ref.Name(): raise exceptions.InvalidArgumentException( 'version', 'version id must be non-empty.') version = client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions.Get( # pylint: disable=line-too-long messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest( name=version_ref.RelativeName())) # Raise exception if --attestation-file is provided for software # key versions. if (args.attestation_file and version.protectionLevel != messages.CryptoKeyVersion.ProtectionLevelValueValuesEnum.HSM): raise kms_exceptions.ArgumentError( 'Attestations are only available for HSM key versions.') if (args.attestation_file and version.state == messages. CryptoKeyVersion.StateValueValuesEnum.PENDING_GENERATION): raise kms_exceptions.ArgumentError( 'The attestation is unavailable until the version is generated.' ) if args.attestation_file and version.attestation is not None: try: log.WriteToFileOrStdout(args.attestation_file, version.attestation.content, overwrite=True, binary=True) except files.Error as e: raise exceptions.BadFileException(e) if version.attestation is not None: # Suppress the attestation content in the printed output. Users can use # --attestation-file to obtain it, instead. version.attestation.content = None # Suppress the attestation content in the printed output. Users can use # get-certificate-chain to obtain it, instead. version.attestation.certChains = None return version
def Run(self, args): client, messages = util.GetClientAndMessages() result = client.projects_serviceAccounts_keys.Create( messages.IamProjectsServiceAccountsKeysCreateRequest( name=iam_util.EmailToAccountResourceName(args.iam_account), createServiceAccountKeyRequest= messages.CreateServiceAccountKeyRequest( privateKeyType=iam_util.KeyTypeToCreateKeyType( iam_util.KeyTypeFromString(args.key_file_type))))) # Only the creating user has access. Set file permission to "-rw-------". log.WriteToFileOrStdout( args.output, content=result.privateKeyData, binary=True, private=True) log.status.Print( 'created key [{0}] of type [{1}] as [{2}] for [{3}]'.format( iam_util.GetKeyIdFromResourceName(result.name), iam_util.KeyTypeToString(result.privateKeyType), args.output, args.iam_account))
def Run(self, args): client = cloudkms_base.GetClientInstance() req = self._CreateMacVerifyRequest(args) try: resp = ( client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions .MacVerify(req)) # Intercept INVALID_ARGUMENT errors related to checksum verification, to # present a user-friendly message. All other errors are surfaced as-is. except apitools_exceptions.HttpBadRequestError as error: e2e_integrity.ProcessHttpBadRequestError(error) if self._PerformIntegrityVerification(args): self._VerifyResponseIntegrityFields(req, resp) log.WriteToFileOrStdout( '-', # Write to stdout. resp.success, binary=False)
def Run(self, args): key_ref = resources.REGISTRY.Parse( args.key, collection='iam.projects.serviceAccounts.keys', params={ 'serviceAccountsId': args.iam_account, 'projectsId': '-' }) key = key_ref.keysId result = self.iam_client.projects_serviceAccounts_keys.Get( self.messages.IamProjectsServiceAccountsKeysGetRequest( name=key_ref.RelativeName(), publicKeyType=iam_util.PublicKeyTypeFromString(args.type))) log.WriteToFileOrStdout(args.output_file, content=result.publicKeyData, binary=True) log.status.Print('written key [{0}] for [{2}] as [{1}]'.format( key, args.output_file, args.iam_account))
def Run(self, args): client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() version_ref = flags.ParseCryptoKeyVersionName(args) if not version_ref.Name(): raise exceptions.InvalidArgumentException( 'version', 'version id must be non-empty.') resp = client.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions.GetPublicKey( # pylint: disable=line-too-long messages. CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetPublicKeyRequest( # pylint: disable=line-too-long name=version_ref.RelativeName())) # TODO(b/72555857): Revisit this when we pull this into trunk. log.WriteToFileOrStdout(args.output_file if args.output_file else '-', resp.pem, overwrite=True, binary=False, private=True)
def Run(self, args): client = cloudkms_base.GetClientInstance() req = self._CreateEncryptRequest(args) try: resp = client.projects_locations_keyRings_cryptoKeys.Encrypt(req) # Intercept INVALID_ARGUMENT errors related to checksum verification, to # present a user-friendly message. All other errors are surfaced as-is. except apitools_exceptions.HttpBadRequestError as error: e2e_integrity.ProcessHttpBadRequestError(error) if self._PerformIntegrityVerification(args): self._VerifyResponseIntegrityFields(req, resp) try: log.WriteToFileOrStdout(args.ciphertext_file, resp.ciphertext, binary=True, overwrite=True) except files.Error as e: raise exceptions.BadFileException(e)
def Run(self, args): client = cloudkms_base.GetClientInstance() messages = cloudkms_base.GetMessagesModule() import_job_ref = flags.ParseImportJobName(args) if not import_job_ref.Name(): raise exceptions.InvalidArgumentException( 'import_job', 'import job id must be non-empty.') import_job = client.projects_locations_keyRings_importJobs.Get( # pylint: disable=line-too-long messages.CloudkmsProjectsLocationsKeyRingsImportJobsGetRequest( name=import_job_ref.RelativeName())) # Raise exception if --attestation-file is provided for software # import jobs. if (args.attestation_file and import_job.protectionLevel != messages.ImportJob.ProtectionLevelValueValuesEnum.HSM): raise exceptions.ToolException( 'Attestations are only available for HSM import jobs.') if (args.attestation_file and import_job.state == messages.ImportJob .StateValueValuesEnum.PENDING_GENERATION): raise exceptions.ToolException( 'The attestation is unavailable until the import job is generated.') if args.attestation_file and import_job.attestation is not None: try: log.WriteToFileOrStdout( args.attestation_file, import_job.attestation.content, overwrite=True, binary=True) except files.Error as e: raise exceptions.BadFileException(e) if import_job.attestation is not None: # Suppress the attestation content in the printed output. Users can use # --attestation-file to obtain it, instead. import_job.attestation.content = None return import_job
def Run(self, args): log.status.Print('Validating input arguments.') project_id = properties.VALUES.core.project.GetOrFail() # Validate the args value before generate the RBAC policy file. rbac_util.ValidateArgs(args) # Revoke RBAC policy for specified user from cluster. if args.revoke: sys.stdout.write( 'Revoking the RBAC policy from cluster with kubeconfig: {}, context: {}\n' .format(args.kubeconfig, args.context)) with kube_util.KubernetesClient( kubeconfig=getattr(args, 'kubeconfig', None), context=getattr(args, 'context', None), ) as kube_client: # Check Admin permissions. kube_client.CheckClusterAdminPermissions() users_list = list() if args.users: users_list = args.users.split(',') elif args.anthos_support: users_list.append( rbac_util.GetAnthosSupportUser(project_id)) for user in users_list: message = ('The RBAC policy for user: {} will be clean up.' .format(user)) console_io.PromptContinue(message=message, cancel_on_no=True) log.status.Print( '--------------------------------------------') log.status.Print( 'Start cleaning up RBAC policy for: {}'.format(user)) if kube_client.CleanUpRbacPolicy(args.membership, args.role, project_id, user, args.anthos_support): log.status.Print( 'Finish clean up the previous RBAC policy for: {}'. format(user)) return # Generate the RBAC policy file from args. generated_rbac = rbac_util.GenerateRBAC(args, project_id) if args.rbac_output_file: sys.stdout.write( 'Generated RBAC policy is written to file: {} \n'.format( args.rbac_output_file)) else: sys.stdout.write('Generated RBAC policy is: \n') sys.stdout.write('--------------------------------------------\n') # Write the generated RBAC policy file to the file provided with # "--rbac-output-file" specified or print on the screen. final_rbac_policy = '' for user in sorted(generated_rbac.keys()): final_rbac_policy += generated_rbac.get(user) log.WriteToFileOrStdout( args.rbac_output_file if args.rbac_output_file else '-', final_rbac_policy, overwrite=True, binary=False, private=True) # Apply generated RBAC policy to cluster. if args.apply: sys.stdout.write( 'Applying the generate RBAC policy to cluster with kubeconfig: {}, context: {}\n' .format(args.kubeconfig, args.context)) with kube_util.KubernetesClient( kubeconfig=getattr(args, 'kubeconfig', None), context=getattr(args, 'context', None), ) as kube_client: # Check Admin permissions. kube_client.CheckClusterAdminPermissions() for user in generated_rbac.keys(): with file_utils.TemporaryDirectory() as tmp_dir: file = tmp_dir + '/rbac.yaml' current_rbac_policy = generated_rbac.get(user) file_utils.WriteFileContents(file, current_rbac_policy) # Check whether there are existing RBAC policy for this user, if not, # will directly apply the new RBAC policy. if not kube_client.GetRbacPolicy( args.membership, args.role, project_id, user, args.anthos_support): # Check whether there are role confliction, which required clean up. need_clean_up = False # Override when proposed RBAC policy has diff with existing one. override_check = False # Checking RBAC policy diff, return None, None if there are no diff. diff, err = kube_client.GetRbacPolicyDiff(file) if diff is not None: override_check = True log.status.Print( 'The new RBAC policy has diff with previous: \n {}' .format(diff)) if err is not None: # 'Invalid value' means the clusterrole/role permission has been # changed. This need to clean up old RBAC policy and then apply # the new one. if 'Invalid value' in err: rbac_policy_name = kube_client.RbacPolicyName( 'permission', project_id, args.membership, user) rbac_permission_policy = kube_client.GetRbacPermissionPolicy( rbac_policy_name, args.role) log.status.Print( 'The existing RBAC policy has conflict with proposed one:\n{}' .format(rbac_permission_policy)) need_clean_up = True override_check = True else: raise exceptions.Error( 'Error when get diff for RBAC policy files for user: {}, with error: {}' .format(user, err)) if override_check: message = ('The RBAC file will be overridden.') console_io.PromptContinue(message=message, cancel_on_no=True) if need_clean_up: log.status.Print( '--------------------------------------------' ) log.status.Print( 'Start cleaning up previous RBAC policy for: {}' .format(user)) if kube_client.CleanUpRbacPolicy( args.membership, args.role, project_id, user, args.anthos_support): log.status.Print( 'Finish clean up the previous RBAC policy for: {}' .format(user)) try: log.status.Print( 'Writing RBAC policy for user: {} to cluster.'. format(user)) kube_client.ApplyRbacPolicy(file) except Exception as e: log.status.Print( 'Error in applying the RBAC policy to cluster: {}' .format(e)) raise log.status.Print( 'Successfully applied the RBAC policy to cluster.')