CFB decryption algorithm incorrect (and buffer overrun)

Bug #1423537 reported by Gene
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Python-Crypto
New
Undecided
Unassigned

Bug Description

The CFB algorithm is show in:
   http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Feedback_.28CFB.29

Although the key encryption function is used in both encrypting and decrypting, the encrypting and decrypting algorithms are different, the are incorrectly the same in the pycrypto-2.6.1 code.

src/block_template.c:

1) in ALG_Encrypt(ALGobject *self, PyObject *args)
in case(MODE_CFB):
line 548

the cipertext not the plaintext is used as the next IV, so the:
     for (j=0; j<self->segment_size/8; j++) {
  buffer[i+j] = str[i+j] ^ temp[j];
     }

should be AFTER the:
    if (self->segment_size == BLOCK_SIZE * 8) {
        ...

2) line 553
   buffer[i+j] = str[i+j] ^ temp[j];

can write past the end if 'buffer' which is 'len' bytes long.

the code with both bugs fixed is:
-----------------------------------------------------------
src/block_template.c:548

 case(MODE_CFB):
  for(i=0; i<len; i+=self->segment_size/8)
  {
   block_encrypt(&(self->st), self->IV, temp);

                        if (self->segment_size == BLOCK_SIZE * 8) {
    /* s == b: segment size is identical to
       the algorithm block size */
    memcpy(self->IV, str + i, BLOCK_SIZE);
   }
   else if ((self->segment_size % 8) == 0) {
    int sz = self->segment_size/8;
    memmove(self->IV, self->IV + sz,
     BLOCK_SIZE-sz);
    memcpy(self->IV + BLOCK_SIZE - sz, str + i,
           sz);
   }
   else {
    /* segment_size is not a multiple of 8;
       currently this can't happen */
   }

   int segmentSize = self->segment_size / 8;
   if (i + segmentSize > len) {
          /* do not overwrite past end of 'buf' */
           segmentSize = len - i;
   }
   for (int j = 0; j < segmentSize; j++) {
          buf[i + j] = buf[i + j] ^ temp[j];
   }

  }
  break;

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.