be afraid, be very afraid...
If you base64 encode a buffer that's not a nice multiple of 3, you get
padding (=) bytes. When you decode those padding bytes, you should
get back a correctly sized buffer, but b64_pton doesn't quite know this.
It tries to write past the end sometimes.
Test string below. It should decode into a 128 byte buffer, but pton
returns -1.
p1v3+nehH3N3n+/OokzXpsyGF2VVpxIxkjSn3Mv/Sq74OE1iFuVU+K4bQImuVj
S55RB2fpCpbB8Nye7tzrt6h9YPP3yyJfqORDETGmIB4lveZXA4KDxx50F9rYrO
dFbTLyWfNBb/8Q2TnD72eY/3Y5P9qwtJwyDL25Tleic8G3g=
The fix is to only write to the next byte if we actually need to write
something.
Index: net/base64.c
===================================================================
RCS file: /cvs/src/lib/libc/net/base64.c,v
retrieving revision 1.6
diff -u -p -r1.6 base64.c
--- net/base64.c 24 Nov 2013 23:51:28 -0000 1.6
+++ net/base64.c 23 Dec 2013 19:42:23 -0000
@@ -194,6 +194,7 @@ b64_pton(src, target, targsize)
size_t targsize;
{
int tarindex, state, ch;
+ u_char nextbyte;
char *pos;
state = 0;
@@ -221,22 +222,28 @@ b64_pton(src, target, targsize)
break;
case 1:
if (target) {
- if (tarindex + 1 >= targsize)
+ if (tarindex >= targsize)
return (-1);
target[tarindex] |= (pos - Base64) >> 4;
- target[tarindex+1] = ((pos - Base64) & 0x0f)
- << 4 ;
+ nextbyte = ((pos - Base64) & 0x0f) << 4;
+ if (nextbyte && tarindex + 1 >= targsize)
+ return (-1);
+ if (tarindex + 1 < targsize)
+ target[tarindex+1] = nextbyte;
}
tarindex++;
state = 2;
break;
case 2:
if (target) {
- if (tarindex + 1 >= targsize)
+ if (tarindex >= targsize)
return (-1);
target[tarindex] |= (pos - Base64) >> 2;
- target[tarindex+1] = ((pos - Base64) & 0x03)
- << 6;
+ nextbyte = ((pos - Base64) & 0x03) << 6;
+ if (nextbyte && tarindex + 1 >= targsize)
+ return (-1);
+ if (tarindex + 1 < targsize)
+ target[tarindex+1] = nextbyte;
}
tarindex++;
state = 3;
@@ -292,7 +299,8 @@ b64_pton(src, target, targsize)
* zeros. If we don't check them, they become a
* subliminal channel.
*/
- if (target && target[tarindex] != 0)
+ if (target && tarindex < targsize &&
+ target[tarindex] != 0)
return (-1);
}
} else {