don't try writing past the end unless we have to
authortedu <tedu@openbsd.org>
Tue, 31 Dec 2013 02:32:56 +0000 (02:32 +0000)
committertedu <tedu@openbsd.org>
Tue, 31 Dec 2013 02:32:56 +0000 (02:32 +0000)
ok gilles millert

lib/libc/net/base64.c

index 78ef449..7c3d1d3 100644 (file)
@@ -1,4 +1,4 @@
-/*     $OpenBSD: base64.c,v 1.6 2013/11/24 23:51:28 deraadt Exp $      */
+/*     $OpenBSD: base64.c,v 1.7 2013/12/31 02:32:56 tedu Exp $ */
 
 /*
  * Copyright (c) 1996 by Internet Software Consortium.
@@ -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 (tarindex + 1 < targsize)
+                                       target[tarindex+1] = nextbyte;
+                               else if (nextbyte)
+                                       return (-1);
                        }
                        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 (tarindex + 1 < targsize)
+                                       target[tarindex+1] = nextbyte;
+                               else if (nextbyte)
+                                       return (-1);
                        }
                        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 {