Python sys.exc_info() Examples

The following are 30 code examples of sys.exc_info(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 8 votes vote down vote up
def get_settings(self):
        """Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
        
        Returns:
            dict -- aws-auto-remediate-settings table
        """
        settings = {}
        try:
            for record in boto3.client("dynamodb").scan(
                TableName=os.environ["SETTINGSTABLE"]
            )["Items"]:
                record_json = dynamodb_json.loads(record, True)
                settings[record_json["key"]] = record_json["value"]
        except:
            self.logging.error(
                f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
            )
            self.logging.error(sys.exc_info()[1])

        return settings 
Example #2
Source File: test_http.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_garbage_in(self):
        # Connect without SSL regardless of server.scheme
        c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        c._output(b'gjkgjklsgjklsgjkljklsg')
        c._send_output()
        response = c.response_class(c.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.assertEqual(response.fp.read(22),
                             b'Malformed Request-Line')
            c.close()
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 
Example #3
Source File: reprconf.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_dict(self, raw=False, vars=None):
        """Convert an INI file to a dictionary"""
        # Load INI file into a dict
        result = {}
        for section in self.sections():
            if section not in result:
                result[section] = {}
            for option in self.options(section):
                value = self.get(section, option, raw=raw, vars=vars)
                try:
                    value = unrepr(value)
                except Exception:
                    x = sys.exc_info()[1]
                    msg = ('Config error in section: %r, option: %r, '
                           'value: %r. Config values must be valid Python.' %
                           (section, option, value))
                    raise ValueError(msg, x.__class__.__name__, x.args)
                result[section][option] = value
        return result 
Example #4
Source File: _cprequest.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def respond(self, path_info):
        """Generate a response for the resource at self.path_info. (Core)"""
        try:
            try:
                try:
                    self._do_respond(path_info)
                except (cherrypy.HTTPRedirect, cherrypy.HTTPError):
                    inst = sys.exc_info()[1]
                    inst.set_response()
                    self.stage = 'before_finalize (HTTPError)'
                    self.hooks.run('before_finalize')
                    cherrypy.serving.response.finalize()
            finally:
                self.stage = 'on_end_resource'
                self.hooks.run('on_end_resource')
        except self.throws:
            raise
        except Exception:
            if self.throw_errors:
                raise
            self.handle_error() 
Example #5
Source File: servers.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _start_http_thread(self):
        """HTTP servers MUST be running in new threads, so that the
        main thread persists to receive KeyboardInterrupt's. If an
        exception is raised in the httpserver's thread then it's
        trapped here, and the bus (and therefore our httpserver)
        are shut down.
        """
        try:
            self.httpserver.start()
        except KeyboardInterrupt:
            self.bus.log('<Ctrl-C> hit: shutting down HTTP server')
            self.interrupt = sys.exc_info()[1]
            self.bus.exit()
        except SystemExit:
            self.bus.log('SystemExit raised: shutting down HTTP server')
            self.interrupt = sys.exc_info()[1]
            self.bus.exit()
            raise
        except Exception:
            self.interrupt = sys.exc_info()[1]
            self.bus.log('Error in HTTP server: shutting down',
                         traceback=True, level=40)
            self.bus.exit()
            raise 
Example #6
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def s3_bucket_public_write_prohibited(self, resource_id):
        """Sets the S3 Bucket ACL to "private" to prevent the Bucket from being publicly written to.
        
        Arguments:
            resource_id {string} -- S3 Bucket Name
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_s3.put_bucket_acl(ACL="private", Bucket=resource_id)

            self.logging.info(f"ACL set to 'private' for S3 Bucket '{resource_id}'.")
            return True
        except:
            self.logging.error(
                f"Could not set ACL set to 'private' for S3 Bucket '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #7
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def s3_bucket_public_read_prohibited(self, resource_id):
        """Sets the S3 Bucket ACL to "private" to prevent the Bucket from being publicly read.
        
        Arguments:
            resource_id {string} -- S3 Bucket Name
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_s3.put_bucket_acl(ACL="private", Bucket=resource_id)

            self.logging.info(f"ACL set to 'private' for S3 Bucket '{resource_id}'.")
            return True
        except:
            self.logging.error(
                f"Could not set ACL set to 'private' for S3 Bucket '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #8
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def receive_message(self, queue_url):
        """Retrieves 10 messeges from an SQS Queue
        
        Arguments:
            queue_url {string} -- SQS Queue URL
        
        Returns:
            dictionary -- Dictionary of SQS messeges
        """
        try:
            return self.client_sqs.receive_message(
                QueueUrl=queue_url,
                MessageAttributeNames=["try_count"],
                MaxNumberOfMessages=10,
            )
        except:
            self.logging.error(
                f"Could not retrieve Messages from SQS Queue URL '{queue_url}'."
            )
            self.logging.error(sys.exc_info()[1])
            return {} 
Example #9
Source File: lex.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def get_caller_module_dict(levels):
    try:
        raise RuntimeError
    except RuntimeError:
        e,b,t = sys.exc_info()
        f = t.tb_frame
        while levels > 0:
            f = f.f_back                   
            levels -= 1
        ldict = f.f_globals.copy()
        if f.f_globals != f.f_locals:
            ldict.update(f.f_locals)

        return ldict

# -----------------------------------------------------------------------------
# _funcs_to_names()
#
# Given a list of regular expression functions, this converts it to a list
# suitable for output to a table file
# ----------------------------------------------------------------------------- 
Example #10
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def get_current_stacks(self):
        """Retrieve a list of all CloudFormation Stacks currently deployed your AWS accont and region
        
        Returns:
            list -- List of currently deployed AWS Config Rules
        """
        try:
            resources = self.client_cloudformation.list_stacks().get("StackSummaries")
        except:
            self.logging.error(sys.exc_info()[1])
            return None

        existing_stacks = []
        for resource in resources:
            if resource.get("StackStatus") not in ("DELETE_COMPLETE"):
                existing_stacks.append(resource.get("StackName"))

        return existing_stacks 
Example #11
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def get_settings(self):
        """Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
        
        Returns:
            dict -- aws-auto-remediate-settings table
        """
        settings = {}
        try:
            for record in self.client_dynamodb.scan(
                TableName=os.environ["SETTINGSTABLE"]
            )["Items"]:
                record_json = dynamodb_json.loads(record, True)

                if "key" in record_json and "value" in record_json:
                    settings[record_json.get("key")] = record_json.get("value")
        except:
            self.logging.error(
                f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
            )
            self.logging.error(sys.exc_info()[1])

        return settings 
Example #12
Source File: yacc.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def get_caller_module_dict(levels):
    try:
        raise RuntimeError
    except RuntimeError:
        e,b,t = sys.exc_info()
        f = t.tb_frame
        while levels > 0:
            f = f.f_back                   
            levels -= 1
        ldict = f.f_globals.copy()
        if f.f_globals != f.f_locals:
            ldict.update(f.f_locals)

        return ldict

# -----------------------------------------------------------------------------
# parse_grammar()
#
# This takes a raw grammar rule string and parses it into production data
# ----------------------------------------------------------------------------- 
Example #13
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def multi_region_cloud_trail_enabled(self, resource_id):
        """Enables multi region CloudTrail
        
        Arguments:
            resource_id {string} -- CloudTrail Name
        
        Returns:
            boolean -- True if remediation is successful
        """
        try:
            self.client_cloudtrail.update_trail(
                Name=resource_id, IsMultiRegionTrail=True
            )
            self.logging.info(
                f"Enabled multi region trail for CloudTrail '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not enable multi region trail for CloudTrail '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #14
Source File: versioneer.py    From aospy with Apache License 2.0 6 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #15
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def mfa_enabled_for_iam_console_access(self, resource_id):
        """Deletes login profile for user with console access that doesn't have MFA enabled

        Arguments:
            resource_id {string} -- IAM User ID

        Returns:
            boolean -- True if remediation is successful
        """
        try:
            page_user = self.client_iam.get_paginator("list_users").paginate()
            for username in page_user.search(
                f"Users[?UserId == '{resource_id}'].UserName"
            ):
                self.client_iam.delete_login_profile(UserName=username)
                self.logging.info(f"Deleted login profile for IAM User '{username}'.")
                return True
        except:
            self.logging.error(
                f"Could not delete login profile for IAM User '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #16
Source File: anim.py    From CAMISIM with Apache License 2.0 5 votes vote down vote up
def last_exception():
		"""
		Returns last exception as a string, or use in logging.

		@rtype: str|unicode
		"""
		exc_type, exc_value, exc_traceback = sys.exc_info()
		return ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))

	# Parse NUCmer delta output to store alignment total length, sim_error,
	# and percentage identity, for each pairwise comparison 
Example #17
Source File: python.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def evalcmd(self, message):
        """.eval <expression>
           Evaluates python code"""
        ret = self.strings["evaluated"]
        try:
            it = await meval(utils.get_args_raw(message), globals(), **await self.getattrs(message))
        except Exception:
            exc = sys.exc_info()
            exc = "".join(traceback.format_exception(exc[0], exc[1], exc[2].tb_next.tb_next.tb_next))
            await utils.answer(message, self.strings["evaluate_fail"]
                               .format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(exc)))
            return
        ret = ret.format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(it))
        await utils.answer(message, ret) 
Example #18
Source File: _version.py    From NiBetaSeries with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #19
Source File: python.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def execcmd(self, message):
        """.exec <expression>
           Executes python code"""
        try:
            await meval(utils.get_args_raw(message), globals(), **await self.getattrs(message))
        except Exception:
            exc = sys.exc_info()
            exc = "".join(traceback.format_exception(exc[0], exc[1], exc[2].tb_next.tb_next.tb_next))
            await utils.answer(message, self.strings["execute_fail"]
                               .format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(exc)))
            return 
Example #20
Source File: versioneer.py    From NiBetaSeries with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #21
Source File: wrappers.py    From soccer-matlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _worker(self, constructor, conn):
    """The process waits for actions and sends back environment results.

    Args:
      constructor: Constructor for the OpenAI Gym environment.
      conn: Connection for communication to the main process.
    """
    try:
      env = constructor()
      while True:
        try:
          # Only block for short times to have keyboard exceptions be raised.
          if not conn.poll(0.1):
            continue
          message, payload = conn.recv()
        except (EOFError, KeyboardInterrupt):
          break
        if message == self._ACTION:
          action = payload
          conn.send((self._TRANSITION, env.step(action)))
          continue
        if message == self._RESET:
          assert payload is None
          conn.send((self._OBSERV, env.reset()))
          continue
        if message == self._ATTRIBUTE:
          name = payload
          conn.send((self._VALUE, getattr(env, name)))
          continue
        if message == self._CLOSE:
          assert payload is None
          break
        raise KeyError('Received message of unknown type {}'.format(message))
    except Exception:  # pylint: disable=broad-except
      stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
      conn.send((self._EXCEPTION, stacktrace))
      tf.logging.error('Error in environment process: {}'.format(stacktrace))
    conn.close() 
Example #22
Source File: wrappers.py    From soccer-matlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _worker(self, constructor, conn):
    """The process waits for actions and sends back environment results.

    Args:
      constructor: Constructor for the OpenAI Gym environment.
      conn: Connection for communication to the main process.
    """
    try:
      env = constructor()
      while True:
        try:
          # Only block for short times to have keyboard exceptions be raised.
          if not conn.poll(0.1):
            continue
          message, payload = conn.recv()
        except (EOFError, KeyboardInterrupt):
          break
        if message == self._ACCESS:
          name = payload
          result = getattr(env, name)
          conn.send((self._RESULT, result))
          continue
        if message == self._CALL:
          name, args, kwargs = payload
          result = getattr(env, name)(*args, **kwargs)
          conn.send((self._RESULT, result))
          continue
        if message == self._CLOSE:
          assert payload is None
          break
        raise KeyError('Received message of unknown type {}'.format(message))
    except Exception:  # pylint: disable=broad-except
      stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
      tf.logging.error('Error in environment process: {}'.format(stacktrace))
      conn.send((self._EXCEPTION, stacktrace))
    conn.close() 
Example #23
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def delete_role_policy(self, role_name, iam_policy_name):
        try:
            self.client_iam.delete_role_policy(
                RoleName=role_name, PolicyName=iam_policy_name
            )
            self.logging.info(
                f"Deleted IAM Policy '{iam_policy_name}' from IAM Role '{role_name}'."
            )
        except:
            self.logging.error(
                f"Could not delete IAM Policy '{iam_policy_name}' from IAM Role '{role_name}'."
            )
            self.logging.error(sys.exc_info()[1])

    # KMS 
Example #24
Source File: _version.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen(
                [c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)
            )
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #25
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def restricted_ssh(self, resource_id):
        """Deletes inbound rules within Security Groups that match:
            Protocol: TCP
            Port: 22
            Source: 0.0.0.0/0 or ::/0
        
        Arguments:
            resource_id {string} -- EC2 Security Group ID
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_ec2.revoke_security_group_ingress(
                GroupId=resource_id,
                IpPermissions=[
                    {
                        "FromPort": 22,
                        "ToPort": 22,
                        "IpProtocol": "tcp",
                        "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
                    },
                    {
                        "FromPort": 22,
                        "ToPort": 22,
                        "IpProtocol": "tcp",
                        "Ipv6Ranges": [{"CidrIpv6": "::/0"}],
                    },
                ],
            )

            self.logging.info(
                f"Revoked public port 22 ingress rule for Security Group '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not revoke public port 22 ingress rule for Security Group '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #26
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def iam_user_no_policies_check(self, resource_id):
        """ Detaches user policies from IAM user

        Arguments:
            resource_id {string} -- IAM User ID

        Returns:
            boolean -- True if remediation was successful
        """
        try:
            page_user = self.client_iam.get_paginator("list_users").paginate()
            for username in page_user.search(
                f"Users[?UserId == '{resource_id}'].UserName"
            ):
                page_policy = self.client_iam.get_paginator(
                    "list_attached_user_policies"
                ).paginate(UserName=username)
                for policy_arn in page_policy.search(f"AttachedPolicies[].PolicyArn"):
                    self.client_iam.detach_user_policy(
                        UserName=username, PolicyArn=policy_arn
                    )
                    self.logging.info(
                        f"Detached IAM Policy '{policy_arn}' from IAM User '{username}'."
                    )
                    return True
        except:
            self.logging.error(
                f"Could not detach IAM Policy '{policy_arn}' from IAM User '{username}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #27
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def iam_password_policy(self, resource_id):
        """Applies a sensible IAM password policy, as per CIS AWS Foundations Standard Checks Supported in Security Hub
        1.5 - Ensure IAM password policy requires at least one uppercase letter
        1.6 - Ensure IAM password policy requires at least one lowercase letter
        1.7 - Ensure IAM password policy requires at least one symbol
        1.8 - Ensure IAM password policy requires at least one number
        1.9 - Ensure IAM password policy requires a minimum length of 14 or greater
        1.10 - Ensure IAM password policy prevents password reuse
        1.11 - Ensure IAM password policy expires passwords within 90 days or less
        
        Arguments:
            resource_id {string} -- AWS Account ID
        
        Returns:
            boolean -- True if remediation was succesfull
        """
        try:
            self.client_iam.update_account_password_policy(
                MinimumPasswordLength=14,  # 14 characters
                RequireSymbols=True,
                RequireNumbers=True,
                RequireUppercaseCharacters=True,
                RequireLowercaseCharacters=True,
                AllowUsersToChangePassword=True,
                MaxPasswordAge=90,  # days
                PasswordReusePrevention=24,  # last 24 passwords
                HardExpiry=False,
            )
            self.logging.info(
                f"Updated IAM password policy with CIS AWS Foundations "
                f"requirements for Account '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not update IAM password policy for Account '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #28
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def cmk_backing_key_rotation_enabled(self, resource_id):
        """Enables key rotation for KMS Customer Managed Keys.
        
        Arguments:
            resource_id {string} -- KMS Key ID
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_kms.enable_key_rotation(KeyId=resource_id)
            self.logging.info(
                f"Enabled key rotation for KMS Customer Managed Key '{resource_id}'."
            )
            return True
        except self.client_kms.exceptions.KMSInvalidStateException:
            self.logging.warning(
                f"Could not enable key rotation for KMS Customer Managed Key '{resource_id}' due to invalid state."
            )
            self.logging.warning(sys.exc_info()[1])
            return False
        except:
            self.logging.error(
                f"Could not enable key rotation for KMS Customer Managed Key '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #29
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 5 votes vote down vote up
def access_keys_rotated(self, resource_id):
        """Deletes IAM User's Access Keys over 90 days old.
        
        Arguments:
            resource_id {string} -- IAM Access Key ID
        
        Returns:
            boolean -- True if remediation is successful
        """
        try:
            response = self.client_iam.get_access_key_last_used(AccessKeyId=resource_id)
        except:
            self.logging.error(
                f"Could not retrieve IAM User Name for IAM Access Key '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False
        else:
            user_name = response["UserName"]
            self.logging.info(
                f"Retrieved IAM User Name '{user_name}' for IAM Access Key '{resource_id}'."
            )

        try:
            self.client_iam.delete_access_key(
                UserName=user_name, AccessKeyId=resource_id
            )
            self.logging.info(
                f"Deleted unrotated IAM Access Key '{resource_id}' for IAM User Name '{user_name}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not delete unrotated IAM Access Key '{resource_id}' for IAM User Name '{user_name}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #30
Source File: versioneer.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode