MCPcopy Create free account
hub / github.com/XTLS/Go / extractPadding

Function extractPadding

conn.go:299–344  ·  view source on GitHub ↗

extractPadding returns, in constant time, the length of the padding to remove from the end of payload. It also returns a byte which is equal to 255 if the padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.

(payload []byte)

Source from the content-addressed store, hash-verified

297// from the end of payload. It also returns a byte which is equal to 255 if the
298// padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
299func extractPadding(payload []byte) (toRemove int, good byte) {
300 if len(payload) < 1 {
301 return 0, 0
302 }
303
304 paddingLen := payload[len(payload)-1]
305 t := uint(len(payload)-1) - uint(paddingLen)
306 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
307 good = byte(int32(^t) >> 31)
308
309 // The maximum possible padding length plus the actual length field
310 toCheck := 256
311 // The length of the padded data is public, so we can use an if here
312 if toCheck > len(payload) {
313 toCheck = len(payload)
314 }
315
316 for i := 0; i < toCheck; i++ {
317 t := uint(paddingLen) - uint(i)
318 // if i <= paddingLen then the MSB of t is zero
319 mask := byte(int32(^t) >> 31)
320 b := payload[len(payload)-1-i]
321 good &^= mask&paddingLen ^ mask&b
322 }
323
324 // We AND together the bits of good and replicate the result across
325 // all the bits.
326 good &= good << 4
327 good &= good << 2
328 good &= good << 1
329 good = uint8(int8(good) >> 7)
330
331 // Zero the padding length on error. This ensures any unchecked bytes
332 // are included in the MAC. Otherwise, an attacker that could
333 // distinguish MAC failures from padding failures could mount an attack
334 // similar to POODLE in SSL 3.0: given a good ciphertext that uses a
335 // full block's worth of padding, replace the final block with another
336 // block. If the MAC check passed but the padding check failed, the
337 // last byte of that block decrypted to the block size.
338 //
339 // See also macAndPaddingGood logic below.
340 paddingLen &= good
341
342 toRemove = int(paddingLen) + 1
343 return
344}
345
346func roundUp(a, b int) int {
347 return a + (b-a%b)%b

Callers 1

decryptMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…