File: __init__.py

package info (click to toggle)
python-ssdeep 3.1%2Bdfsg-3
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 140 kB
  • sloc: python: 424; makefile: 11
file content (245 lines) | stat: -rw-r--r-- 7,342 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""
This is a straightforward Python wrapper for ssdeep by Jesse Kornblum,
which is a library for computing Context Triggered Piecewise Hashes (CTPH).
"""

import os

import six

from ssdeep.__about__ import (
    __author__, __copyright__, __email__, __license__, __summary__, __title__,
    __uri__, __version__
)
from ssdeep.binding import Binding

binding = Binding()
ffi = binding.ffi


class BaseError(Exception):
    """The base for all other Exceptions"""
    pass


class InternalError(BaseError):
    """Raised if lib returns internal error"""
    pass


class Hash(object):
    """
    Hashlib like object. It is only supported with ssdeep/libfuzzy >= 2.10.

    :raises InternalError: If lib returns internal error
    :raises NotImplementedError: Required functions are not available
    """
    def __init__(self):
        self._state = ffi.NULL

        if not hasattr(binding.lib, "fuzzy_new"):
            raise NotImplementedError("Only supported with ssdeep >= 2.10")

        self._state = binding.lib.fuzzy_new()
        if self._state == ffi.NULL:
            raise InternalError("Unable to create state object")

    def update(self, buf, encoding="utf-8"):
        """
         Feed the data contained in the given buffer to the state.

        :param String|Byte buf: The data to be hashed
        :param String encoding: Encoding is used if buf is String
        :raises InternalError: If lib returns an internal error
        :raises TypeError: If buf is not Bytes, String or Unicode

        """

        if self._state == ffi.NULL:
            raise InternalError("State object is NULL")

        if isinstance(buf, six.text_type):
            buf = buf.encode(encoding)

        if not isinstance(buf, six.binary_type):
            raise TypeError(
                "Argument must be of string, unicode or bytes type not "
                "'%r'" % type(buf)
            )

        if binding.lib.fuzzy_update(self._state, buf, len(buf)) != 0:
            binding.lib.fuzzy_free(self._state)
            raise InternalError("Invalid state object")

    def digest(self, elimseq=False, notrunc=False):
        """
        Obtain the fuzzy hash.

        This operation does not change the state at all. It reports the hash
        for the concatenation of the data previously fed using update().

        :return: The fuzzy hash
        :rtype: String
        :raises InternalError: If lib returns an internal error

        """

        if self._state == ffi.NULL:
            raise InternalError("State object is NULL")

        flags = (binding.lib.FUZZY_FLAG_ELIMSEQ if elimseq else 0) | \
                (binding.lib.FUZZY_FLAG_NOTRUNC if notrunc else 0)

        result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
        if binding.lib.fuzzy_digest(self._state, result, flags) != 0:
            raise InternalError("Function returned an unexpected error code")

        return ffi.string(result).decode("ascii")

    def __del__(self):
        if self._state != ffi.NULL:
            binding.lib.fuzzy_free(self._state)


class PseudoHash(object):
    """
    Hashlib like object. Use this class only if Hash() isn't supported by your
    ssdeep/libfuzzy library. This class stores the provided data in memory, so
    be careful when hashing large files.

    """
    def __init__(self):
        self._data = b""

    def update(self, buf, encoding="utf-8"):
        """
         Feed the data contained in the given buffer to the state.

        :param String|Byte buf: The data to be hashed
        :param String encoding: Encoding is used if buf is String
        :raises TypeError: If buf is not Bytes, String or Unicode

        """

        if isinstance(buf, six.text_type):
            buf = buf.encode(encoding)

        if not isinstance(buf, six.binary_type):
            raise TypeError(
                "Argument must be of string, unicode or bytes type not "
                "'%r'" % type(buf)
            )

        self._data = self._data + buf

    def digest(self, elimseq=False, notrunc=False):
        """
        Obtain the fuzzy hash.

        This operation does not change the state at all. It reports the hash
        for the concatenation of the data previously fed using update().

        :return: The fuzzy hash
        :rtype: String

        """

        return hash(self._data)


def compare(sig1, sig2):
    """
    Computes the match score between two fuzzy hash signatures.

    Returns a value from zero to 100 indicating the match score of the
    two signatures. A match score of zero indicates the signatures
    did not match.

    :param Bytes|String sig1: First fuzzy hash signature
    :param Bytes|String sig2: Second fuzzy hash signature
    :return: Match score (0-100)
    :rtype: Integer
    :raises InternalError: If lib returns an internal error
    :raises TypeError: If sig is not String, Unicode or Bytes

    """

    if isinstance(sig1, six.text_type):
        sig1 = sig1.encode("ascii")
    if isinstance(sig2, six.text_type):
        sig2 = sig2.encode("ascii")

    if not isinstance(sig1, six.binary_type):
        raise TypeError(
            "First argument must be of string, unicode or bytes type not "
            "'%s'" % type(sig1)
        )

    if not isinstance(sig2, six.binary_type):
        raise TypeError(
            "Second argument must be of string, unicode or bytes type not "
            "'%r'" % type(sig2)
        )

    res = binding.lib.fuzzy_compare(sig1, sig2)
    if res < 0:
        raise InternalError("Function returned an unexpected error code")

    return res


def hash(buf, encoding="utf-8"):
    """
    Compute the fuzzy hash of a buffer

    :param String|Bytes buf: The data to be fuzzy hashed
    :return: The fuzzy hash
    :rtype: String
    :raises InternalError: If lib returns an internal error
    :raises TypeError: If buf is not String or Bytes

    """

    if isinstance(buf, six.text_type):
        buf = buf.encode(encoding)

    if not isinstance(buf, six.binary_type):
        raise TypeError(
            "Argument must be of string, unicode or bytes type not "
            "'%r'" % type(buf)
        )

    # allocate memory for result
    result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
    if binding.lib.fuzzy_hash_buf(buf, len(buf), result) != 0:
        raise InternalError("Function returned an unexpected error code")

    return ffi.string(result).decode("ascii")


def hash_from_file(filename):
    """
    Compute the fuzzy hash of a file.

    Opens, reads, and hashes the contents of the file 'filename'

    :param String|Bytes filename: The name of the file to be hashed
    :return: The fuzzy hash of the file
    :rtype: String
    :raises IOError: If Python is unable to read the file
    :raises InternalError: If lib returns an internal error

    """

    if not os.path.exists(filename):
        raise IOError("Path not found")
    if not os.path.isfile(filename):
        raise IOError("File not found")
    if not os.access(filename, os.R_OK):
        raise IOError("File is not readable")

    result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT)
    if binding.lib.fuzzy_hash_filename(filename.encode("utf-8"), result) != 0:
        raise InternalError("Function returned an unexpected error code")

    return ffi.string(result).decode("ascii")