This file is indexed.

/usr/share/pyshared/passlib/handlers/sha2_crypt.py is in python-passlib 1.5.3-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"""passlib.handlers.sha2_crypt - SHA256/512-CRYPT"""
#=========================================================
#imports
#=========================================================
#core
from hashlib import sha256, sha512
import re
import logging; log = logging.getLogger(__name__)
from warnings import warn
#site
#libs
from passlib.utils import h64, safe_os_crypt, classproperty, handlers as uh, \
    to_hash_str, to_unicode, bytes, b, bord
#pkg
#local
__all__ = [
    "SHA256Crypt",
    "SHA512Crypt",
]

#=========================================================
#pure-python backend (shared between sha256-crypt & sha512-crypt)
#=========================================================
INVALID_SALT_VALUES = b("\x00$")

def raw_sha_crypt(secret, salt, rounds, hash):
    """perform raw sha crypt

    :arg secret: password to encode (if unicode, encoded to utf-8)
    :arg salt: salt string to use (required)
    :arg rounds: int rounds
    :arg hash: hash constructor function for 256/512 variant

    :returns:
        Returns tuple of ``(unencoded checksum, normalized salt, normalized rounds)``.

    """
    #validate secret
    if not isinstance(secret, bytes):
        raise TypeError("secret must be encoded as bytes")

    #validate rounds
    if rounds < 1000:
        rounds = 1000
    if rounds > 999999999: #pragma: no cover
        rounds = 999999999

    #validate salt
    if not isinstance(salt, bytes):
        raise TypeError("salt must be encoded as bytes")
    if any(c in salt for c in INVALID_SALT_VALUES):
        raise ValueError("invalid chars in salt")
    if len(salt) > 16:
        salt = salt[:16]

    #init helpers
    def extend(source, size_ref):
        "helper which repeats <source> digest string until it's the same length as <size_ref> string"
        assert len(source) == chunk_size
        size = len(size_ref)
        return source * int(size/chunk_size) + source[:size % chunk_size]

    #calc digest B
    b = hash(secret)
    chunk_size = b.digest_size #grab this once hash is created
    b.update(salt)
    a = b.copy() #make a copy to save a little time later
    b.update(secret)
    b_result = b.digest()
    b_extend = extend(b_result, secret)

    #begin digest A
    #a = hash(secret) <- performed above
    #a.update(salt) <- performed above
    a.update(b_extend)

    #for each bit in slen, add B or SECRET
    value = len(secret)
    while value > 0:
        if value % 2:
            a.update(b_result)
        else:
            a.update(secret)
        value >>= 1

    #finish A
    a_result = a.digest()

    #calc DP - hash of password, extended to size of password
    dp = hash(secret * len(secret))
    dp_result = extend(dp.digest(), secret)

    #calc DS - hash of salt, extended to size of salt
    ds = hash(salt * (16+bord(a_result[0])))
    ds_result = extend(ds.digest(), salt) #aka 'S'

    #
    #calc digest C
    #NOTE: this has been contorted a little to allow pre-computing
    #some of the hashes. the original algorithm was that
    #each round generates digest composed of:
    #   if round%2>0 => dp else lr
    #   if round%3>0 => ds
    #   if round%7>0 => dp
    #   if round%2>0 => lr else dp
    #where lr is digest of the last round's hash (initially = a_result)
    #

    #pre-calculate some digests to speed up odd rounds
    dp_hash = hash(dp_result).copy
    dp_ds_hash = hash(dp_result + ds_result).copy
    dp_dp_hash = hash(dp_result * 2).copy
    dp_ds_dp_hash = hash(dp_result + ds_result + dp_result).copy

    #pre-calculate some strings to speed up even rounds
    ds_dp_result = ds_result + dp_result
    dp_dp_result = dp_result * 2
    ds_dp_dp_result = ds_result + dp_dp_result

    #run through rounds
    last_result = a_result
    i = 0
    while i < rounds:
        if i % 2:
            if i % 3:
                if i % 7:
                    c = dp_ds_dp_hash()
                else:
                    c = dp_ds_hash()
            elif i % 7:
                c = dp_dp_hash()
            else:
                c = dp_hash()
            c.update(last_result)
        else:
            c = hash(last_result)
            if i % 3:
                if i % 7:
                    c.update(ds_dp_dp_result)
                else:
                    c.update(ds_dp_result)
            elif i % 7:
                c.update(dp_dp_result)
            else:
                c.update(dp_result)
        last_result = c.digest()
        i += 1

    #return unencoded result, along w/ normalized config values
    return last_result, salt, rounds

def raw_sha256_crypt(secret, salt, rounds):
    "perform raw sha256-crypt; returns encoded checksum, normalized salt & rounds"
    #run common crypt routine
    result, salt, rounds = raw_sha_crypt(secret, salt, rounds, sha256)
    out = h64.encode_transposed_bytes(result, _256_offsets)
    assert len(out) == 43, "wrong length: %r" % (out,)
    return out, salt, rounds

_256_offsets = (
    20, 10, 0,
    11, 1,  21,
    2,  22, 12,
    23, 13, 3,
    14, 4,  24,
    5,  25, 15,
    26, 16, 6,
    17, 7,  27,
    8,  28, 18,
    29, 19, 9,
    30, 31,
)

def raw_sha512_crypt(secret, salt, rounds):
    "perform raw sha512-crypt; returns encoded checksum, normalized salt & rounds"
    #run common crypt routine
    result, salt, rounds = raw_sha_crypt(secret, salt, rounds, sha512)

    ###encode result
    out = h64.encode_transposed_bytes(result, _512_offsets)
    assert len(out) == 86, "wrong length: %r" % (out,)
    return out, salt, rounds

_512_offsets = (
    42, 21, 0,
    1,  43, 22,
    23, 2,  44,
    45, 24, 3,
    4,  46, 25,
    26, 5,  47,
    48, 27, 6,
    7,  49, 28,
    29, 8,  50,
    51, 30, 9,
    10, 52, 31,
    32, 11, 53,
    54, 33, 12,
    13, 55, 34,
    35, 14, 56,
    57, 36, 15,
    16, 58, 37,
    38, 17, 59,
    60, 39, 18,
    19, 61, 40,
    41, 20, 62,
    63,
)

#=========================================================
#handler
#=========================================================
class sha256_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler):
    """This class implements the SHA256-Crypt password hash, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`encrypt()` and :meth:`genconfig` methods accept the following optional keywords:

    :param salt:
        Optional salt string.
        If not specified, one will be autogenerated (this is recommended).
        If specified, it must be 0-16 characters, drawn from the regexp range ``[./0-9A-Za-z]``.

    :param rounds:
        Optional number of rounds to use.
        Defaults to 40000, must be between 1000 and 999999999, inclusive.

    :param implicit_rounds:
        this is an internal option which generally doesn't need to be touched.

        this flag determines whether the hash should omit the rounds parameter
        when encoding it to a string; this is only permitted by the spec for rounds=5000,
        and the flag is ignored otherwise. the spec requires the two different
        encodings be preserved as they are, instead of normalizing them.

    It will use the first available of two possible backends:

    * stdlib :func:`crypt()`, if the host OS supports SHA256-Crypt.
    * a pure python implementation of SHA256-Crypt built into passlib.

    You can see which backend is in use by calling the :meth:`get_backend()` method.
    """

    #=========================================================
    #algorithm information
    #=========================================================
    #--GenericHandler--
    name = "sha256_crypt"
    setting_kwds = ("salt", "rounds", "implicit_rounds", "salt_size")
    ident = u"$5$"
    checksum_chars = uh.H64_CHARS

    #--HasSalt--
    min_salt_size = 0
    max_salt_size = 16
    #TODO: allow salt charset 0-255 except for "\x00\n:$"
    salt_chars = uh.H64_CHARS

    #--HasRounds--
    default_rounds = 40000 #current passlib default
    min_rounds = 1000 #other bounds set by spec
    max_rounds = 999999999
    rounds_cost = "linear"

    #=========================================================
    #init
    #=========================================================
    def __init__(self, implicit_rounds=None, **kwds):
        if implicit_rounds is None:
            implicit_rounds = True
        self.implicit_rounds = implicit_rounds
        super(sha256_crypt, self).__init__(**kwds)

    #=========================================================
    #parsing
    #=========================================================

    #: regexp used to parse hashes
    _pat = re.compile(ur"""
        ^
        \$5
        (\$rounds=(?P<rounds>\d+))?
        \$
        (
            (?P<salt1>[^:$]*)
            |
            (?P<salt2>[^:$]{0,16})
            \$
            (?P<chk>[A-Za-z0-9./]{43})?
        )
        $
        """, re.X)

    @classmethod
    def from_string(cls, hash):
        if not hash:
            raise ValueError("no hash specified")
        if isinstance(hash, bytes):
            hash = hash.decode("ascii")
        m = cls._pat.match(hash)
        if not m:
            raise ValueError("invalid sha256-crypt hash")
        rounds, salt1, salt2, chk = m.group("rounds", "salt1", "salt2", "chk")
        if rounds and rounds.startswith(u"0"):
            raise ValueError("invalid sha256-crypt hash (zero-padded rounds)")
        return cls(
            implicit_rounds = not rounds,
            rounds=int(rounds) if rounds else 5000,
            salt=salt1 or salt2,
            checksum=chk,
            strict=bool(chk),
        )

    def to_string(self, native=True):
        if self.rounds == 5000 and self.implicit_rounds:
            hash = u"$5$%s$%s" % (self.salt, self.checksum or u'')
        else:
            hash = u"$5$rounds=%d$%s$%s" % (self.rounds, self.salt, self.checksum or u'')
        return to_hash_str(hash) if native else hash

    #=========================================================
    #backend
    #=========================================================
    backends = ("os_crypt", "builtin")

    _has_backend_builtin = True

    @classproperty
    def _has_backend_os_crypt(cls):
        h = u"$5$rounds=1000$test$QmQADEXMG8POI5WDsaeho0P36yK3Tcrgboabng6bkb/"
        return bool(safe_os_crypt and safe_os_crypt(u"test",h)[1]==h)

    def _calc_checksum_builtin(self, secret):
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        checksum, salt, rounds = raw_sha256_crypt(secret,
                                                  self.salt.encode("ascii"),
                                                  self.rounds)
        assert salt == self.salt.encode("ascii"), \
            "class doesn't agree w/ builtin backend: salt %r != %r" % (salt, self.salt.encode("ascii"))
        assert rounds == self.rounds, \
            "class doesn't agree w/ builtin backend: rounds %r != %r" % (rounds, self.rounds)
        return checksum.decode("ascii")

    def _calc_checksum_os_crypt(self, secret):
        ok, result = safe_os_crypt(secret, self.to_string(native=False))
        if ok:
            #NOTE: avoiding full parsing routine via from_string().checksum,
            # and just extracting the bit we need.
            assert result.startswith(u"$5$")
            chk = result[-43:]
            assert u'$' not in chk
            return chk
        else:
            return self._calc_checksum_builtin(secret)

    #=========================================================
    #eoc
    #=========================================================

#=========================================================
#sha 512 crypt
#=========================================================
class sha512_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler):
    """This class implements the SHA512-Crypt password hash, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`encrypt()` and :meth:`genconfig` methods accept the following optional keywords:

    :param salt:
        Optional salt string.
        If not specified, one will be autogenerated (this is recommended).
        If specified, it must be 0-16 characters, drawn from the regexp range ``[./0-9A-Za-z]``.

    :param rounds:
        Optional number of rounds to use.
        Defaults to 40000, must be between 1000 and 999999999, inclusive.

    :param implicit_rounds:
        this is an internal option which generally doesn't need to be touched.

        this flag determines whether the hash should omit the rounds parameter
        when encoding it to a string; this is only permitted by the spec for rounds=5000,
        and the flag is ignored otherwise. the spec requires the two different
        encodings be preserved as they are, instead of normalizing them.

    It will use the first available of two possible backends:

    * stdlib :func:`crypt()`, if the host OS supports SHA512-Crypt.
    * a pure python implementation of SHA512-Crypt built into passlib.

    You can see which backend is in use by calling the :meth:`get_backend()` method.
    """

    #=========================================================
    #algorithm information
    #=========================================================
    name = "sha512_crypt"
    ident = u"$6$"
    checksum_chars = uh.H64_CHARS

    setting_kwds = ("salt", "rounds", "implicit_rounds", "salt_size")

    min_salt_size = 0
    max_salt_size = 16
    #TODO: allow salt charset 0-255 except for "\x00\n:$"
    salt_chars = uh.H64_CHARS

    default_rounds = 40000 #current passlib default
    min_rounds = 1000
    max_rounds = 999999999
    rounds_cost = "linear"

    #=========================================================
    #init
    #=========================================================
    def __init__(self, implicit_rounds=None, **kwds):
        if implicit_rounds is None:
            implicit_rounds = True
        self.implicit_rounds = implicit_rounds
        super(sha512_crypt, self).__init__(**kwds)

    #=========================================================
    #parsing
    #=========================================================

    #: regexp used to parse hashes
    _pat = re.compile(ur"""
        ^
        \$6
        (\$rounds=(?P<rounds>\d+))?
        \$
        (
            (?P<salt1>[^:$\n]*)
            |
            (?P<salt2>[^:$\n]{0,16})
            (
                \$
                (?P<chk>[A-Za-z0-9./]{86})?
            )?
        )
        $
        """, re.X)

    @classmethod
    def from_string(cls, hash):
        if not hash:
            raise ValueError("no hash specified")
        if isinstance(hash, bytes):
            hash = hash.decode("ascii")
        m = cls._pat.match(hash)
        if not m:
            raise ValueError("invalid sha512-crypt hash")
        rounds, salt1, salt2, chk = m.group("rounds", "salt1", "salt2", "chk")
        if rounds and rounds.startswith("0"):
            raise ValueError("invalid sha512-crypt hash (zero-padded rounds)")
        return cls(
            implicit_rounds = not rounds,
            rounds=int(rounds) if rounds else 5000,
            salt=salt1 or salt2,
            checksum=chk,
            strict=bool(chk),
        )

    def to_string(self, native=True):
        if self.rounds == 5000 and self.implicit_rounds:
            hash = u"$6$%s$%s" % (self.salt, self.checksum or u'')
        else:
            hash = u"$6$rounds=%d$%s$%s" % (self.rounds, self.salt, self.checksum or u'')
        return to_hash_str(hash) if native else hash

    #=========================================================
    #backend
    #=========================================================
    backends = ("os_crypt", "builtin")

    _has_backend_builtin = True

    @classproperty
    def _has_backend_os_crypt(cls):
        h = u"$6$rounds=1000$test$2M/Lx6MtobqjLjobw0Wmo4Q5OFx5nVLJvmgseatA6oMnyWeBdRDx4DU.1H3eGmse6pgsOgDisWBGI5c7TZauS0"
        return bool(safe_os_crypt and safe_os_crypt(u"test",h)[1]==h)

    #NOTE: testing w/ HashTimer shows 64-bit linux's crypt to be ~2.6x faster than builtin (627253 vs 238152 rounds/sec)

    def _calc_checksum_builtin(self, secret):
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        checksum, salt, rounds = raw_sha512_crypt(secret,
                                                  self.salt.encode("ascii"),
                                                  self.rounds)
        assert salt == self.salt.encode("ascii"), \
            "class doesn't agree w/ builtin backend: salt %r != %r" % (salt, self.salt.encode("ascii"))
        assert rounds == self.rounds, \
            "class doesn't agree w/ builtin backend: rounds %r != %r" % (rounds, self.rounds)
        return checksum.decode("ascii")

    def _calc_checksum_os_crypt(self, secret):
        ok, result = safe_os_crypt(secret, self.to_string(native=False))
        if ok:
            #NOTE: avoiding full parsing routine via from_string().checksum,
            # and just extracting the bit we need.
            assert result.startswith(u"$6$")
            chk = result[-86:]
            assert u'$' not in chk
            return chk
        else:
            return self._calc_checksum_builtin(secret)

    #=========================================================
    #eoc
    #=========================================================

#=========================================================
#eof
#=========================================================