Пример #1
0
    def __init__(self, initializer=None, allow_prompt=None):

        if isinstance(initializer, RSAPrivateKey):
            initializer = initializer._value  # pylint: disable=protected-access

        if initializer is None:
            super(RSAPrivateKey, self).__init__(None)
            return

        if isinstance(initializer, rsa.RSAPrivateKey):
            super(RSAPrivateKey, self).__init__(initializer)
            return

        if isinstance(initializer, Text):
            initializer = initializer.encode("ascii")

        if not isinstance(initializer, bytes):
            raise rdfvalue.InitializeError("Cannot initialize %s from %s." %
                                           (self.__class__, initializer))

        try:
            value = serialization.load_pem_private_key(initializer,
                                                       password=None,
                                                       backend=openssl.backend)
            super(RSAPrivateKey, self).__init__(value)
            return
        except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:

            if "private key is encrypted" not in str(e):
                raise type_info.TypeValueError("Private key invalid: %s" % e)

            # The private key is passphrase protected, we need to see if we are
            # allowed to ask the user.
            #
            # In the case where allow_prompt was not set at all, we use the context
            # we are in to see if it makes sense to ask.
            if allow_prompt is None:
                # TODO(user): dependency loop with
                # core/grr_response_core/grr/config/client.py.
                # pylint: disable=protected-access
                if "Commandline Context" not in config_lib._CONFIG.context:
                    raise type_info.TypeValueError("Private key invalid: %s" %
                                                   e)
                # pylint: enable=protected-access

            # Otherwise, if allow_prompt is False, we are explicitly told that we are
            # not supposed to ask the user.
            elif not allow_prompt:
                raise type_info.TypeValueError("Private key invalid: %s" % e)

        try:
            # The private key is encrypted and we can ask the user for the passphrase.
            password = utils.PassphraseCallback()
            value = serialization.load_pem_private_key(initializer,
                                                       password=password,
                                                       backend=openssl.backend)
            super(RSAPrivateKey, self).__init__(value)
        except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:
            raise type_info.TypeValueError("Unable to load private key: %s" %
                                           e)
Пример #2
0
  def Validate(self):
    super(AFF4ObjectLabel, self).Validate()

    if not self.name:
      raise type_info.TypeValueError("Label name cannot be empty.")

    if not re.match("^[\\w./:\\- ]+$", self.name):
      raise type_info.TypeValueError("Label name can only contain: "
                                     "a-zA-Z0-9_./:- but got: '%s'" % self.name)
Пример #3
0
Файл: aff4.py Проект: juju4/grr
    def Validate(self):
        super(AFF4ObjectLabel, self).Validate()

        if not self.name:
            raise type_info.TypeValueError("Label name cannot be empty.")

        is_valid = lambda char: char.isalnum() or char in " _./:-"
        if not all(map(is_valid, self.name)):
            raise type_info.TypeValueError("Label name can only contain: "
                                           "a-zA-Z0-9_./:- but got: '%s'" %
                                           self.name)
Пример #4
0
 def ParseFromBytes(self, pem_string):
     precondition.AssertType(pem_string, bytes)
     try:
         self._value = serialization.load_pem_public_key(
             pem_string, backend=openssl.backend)
     except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:
         raise type_info.TypeValueError("Public key invalid: %s" % e)
Пример #5
0
    def Validate(self, value):
        value = super(PathTypeInfo, self).Validate(value)
        if self.must_exist and not os.access(value, os.R_OK):
            raise type_info.TypeValueError("Path %s does not exist for %s" %
                                           (value, self.name))

        return value
Пример #6
0
    def __init__(self, initializer=None):
        if isinstance(initializer, RSAPublicKey):
            initializer = initializer._value  # pylint: disable=protected-access

        if initializer is None:
            super(RSAPublicKey, self).__init__(None)
            return

        if isinstance(initializer, rsa.RSAPublicKey):
            super(RSAPublicKey, self).__init__(initializer)
            return

        if isinstance(initializer, Text):
            initializer = initializer.encode("ascii")

        if isinstance(initializer, bytes):
            try:
                value = serialization.load_pem_public_key(
                    initializer, backend=openssl.backend)
                super(RSAPublicKey, self).__init__(value)
                return
            except (TypeError, ValueError,
                    exceptions.UnsupportedAlgorithm) as e:
                raise type_info.TypeValueError("Public key invalid: %s" % e)

        raise rdfvalue.InitializeError("Cannot initialize %s from %s." %
                                       (self.__class__, initializer))
Пример #7
0
    def __init__(self, initializer=None):
        super(FilterString, self).__init__(initializer)

        if self._value:
            try:
                self.query_parser_cls(self._value).Parse()
            except lexer.ParseError as e:
                raise type_info.TypeValueError("Malformed filter: %s" % (e))
Пример #8
0
    def ParseFromString(self, value):
        super(RegularExpression, self).ParseFromString(value)

        # Check that this is a valid regex.
        try:
            self._regex = re.compile(self._value, flags=re.I | re.S | re.M)
        except re.error:
            raise type_info.TypeValueError("Not a valid regular expression.")
Пример #9
0
    def ParseFromString(self, pem_string):
        precondition.AssertType(pem_string, bytes)
        try:
            self._value = serialization.load_pem_private_key(
                pem_string, password=None, backend=openssl.backend)
            return
        except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:

            if "private key is encrypted" not in str(e):
                raise type_info.TypeValueError("Private key invalid: %s" % e)

            # pylint: disable=g-explicit-bool-comparison, g-equals-none

            # The private key is passphrase protected, we need to see if we are
            # allowed to ask the user.
            #
            # If allow_prompt is False, we are explicitly told that we are not.
            if self.allow_prompt == False:
                raise type_info.TypeValueError("Private key invalid: %s" % e)

            # allow_prompt was not set, we use the context we are in to see if it
            # makes sense to ask.
            elif self.allow_prompt == None:
                # TODO(user): dependency loop with
                # core/grr_response_core/grr/config/client.py.
                # pylint: disable=protected-access
                if "Commandline Context" not in config_lib._CONFIG.context:
                    raise type_info.TypeValueError("Private key invalid: %s" %
                                                   e)
                # pylint: enable=protected-access

                # pylint: enable=g-explicit-bool-comparison, g-equals-none

        try:
            # The private key is encrypted and we can ask the user for the passphrase.
            password = utils.PassphraseCallback()
            self._value = serialization.load_pem_private_key(
                pem_string, password=password, backend=openssl.backend)
        except (TypeError, ValueError, exceptions.UnsupportedAlgorithm) as e:
            raise type_info.TypeValueError("Unable to load private key: %s" %
                                           e)
Пример #10
0
    def _Normalize(cls, string):
        normalized = super(ClientURN, cls)._Normalize(string.strip())

        if normalized:
            match = cls.CLIENT_ID_RE.match(normalized)
            if not match:
                raise type_info.TypeValueError(
                    "Client URN '{!r} from initializer {!r} malformed".format(
                        normalized, string))

            clientid = match.group("clientid")
            clientid_correctcase = "".join(
                (clientid[0].upper(), clientid[1:].lower()))

            normalized = normalized.replace(clientid, clientid_correctcase, 1)
        return normalized
Пример #11
0
    def DataRefreshRequired(self, path=None, last=None):
        """True if we need to update this path from the client.

    Args:
      path: The path relative to the root to check freshness of.
      last: An aff4:last attribute to check freshness of.

      At least one of path or last must be supplied.

    Returns:
      True if the path hasn't been updated in the last
      self.max_age_before_refresh seconds, else False.

    Raises:
      type_info.TypeValueError: If no arguments are supplied.
    """

        # If we didn't get given a last attribute, use the path to get one from the
        # object.
        if last is None:
            if path is None:
                # If we didn't get a path either, we can't do anything.
                raise type_info.TypeValueError("Either 'path' or 'last' must"
                                               " be supplied as an argument.")

            fd = aff4.FACTORY.Open(self.root.Add(path), token=self.token)
            # We really care about the last time the stat was updated, so we use
            # this instead of the LAST attribute, which is the last time anything
            # was updated about the object.
            stat_obj = fd.Get(fd.Schema.STAT)
            if stat_obj:
                last = stat_obj.age
            else:
                last = rdfvalue.RDFDatetime(0)

        # If the object doesn't even have a LAST attribute by this point,
        # we say it hasn't been accessed within the cache expiry time.
        if last is None:
            return True
        last = last.AsDatetime()

        # Remember to use UTC time, since that's what the datastore uses.
        return datetime.datetime.utcnow() - last > self.max_age_before_refresh
Пример #12
0
  def ParseFromString(self, value):
    """Parse a string into a client URN.

    Convert case so that all URNs are of the form C.[0-9a-f].

    Args:
      value: string value to parse
    """
    value = value.strip()

    super(ClientURN, self).ParseFromString(value)

    match = self.CLIENT_ID_RE.match(self._string_urn)
    if not match:
      raise type_info.TypeValueError("Client urn malformed: %s" % value)

    clientid = match.group("clientid")
    clientid_correctcase = "".join((clientid[0].upper(), clientid[1:].lower()))

    self._string_urn = self._string_urn.replace(clientid, clientid_correctcase,
                                                1)
Пример #13
0
    def __init__(self, initializer=None):
        super().__init__(initializer)

        if self._value and not self.Validate(self._value):
            raise type_info.TypeValueError("Client urn malformed: %s" %
                                           initializer)
Пример #14
0
 def __init__(self, initializer=None, age=None):
     if isinstance(initializer, rdfvalue.RDFURN):
         if not self.Validate(initializer.Path()):
             raise type_info.TypeValueError("Client urn malformed: %s" %
                                            initializer)
     super(ClientURN, self).__init__(initializer=initializer, age=age)
Пример #15
0
 def ParseFromString(self, value):
     super(FilterString, self).ParseFromString(value)
     try:
         self.query_parser_cls(self._value).Parse()
     except lexer.ParseError, e:
         raise type_info.TypeValueError("Malformed filter: %s" % (e))