]> git.parisson.com Git - pdf.js.git/commitdiff
Basic DecryptStream functionality; md5 and arcfour algorithms
authornotmasteryet <async.processingjs@yahoo.com>
Fri, 24 Jun 2011 12:51:31 +0000 (07:51 -0500)
committernotmasteryet <async.processingjs@yahoo.com>
Fri, 24 Jun 2011 12:51:31 +0000 (07:51 -0500)
pdf.js
security.js [new file with mode: 0644]
viewer.html

diff --git a/pdf.js b/pdf.js
index 52a65f1e39fb95315e49be7ab9fc253e663c4f19..320fc6913bb4b32eb4f3b4ee60a56d24c09d3816 100644 (file)
--- a/pdf.js
+++ b/pdf.js
@@ -56,6 +56,14 @@ function bytesToString(bytes) {
     return str;
 }
 
+function stringToBytes(str) {
+    var length = str.length;
+    var bytes = new Uint8Array(length);
+    for (var n = 0; n < length; ++n)
+        bytes[n] = str.charCodeAt(n) & 0xFF;
+    return bytes;
+}
+
 var Stream = (function() {
     function constructor(arrayBuffer, start, length, dict) {
         this.bytes = Uint8Array(arrayBuffer);
@@ -741,11 +749,34 @@ var PredictorStream = (function() {
 })();
 
 var DecryptStream = (function() {
-    function constructor(str, fileKey, encAlgorithm, keyLength) {
-        TODO("decrypt stream is not implemented");
+    function constructor(str, decrypt) {
+        this.str = str;
+        this.dict = str.dict;
+        this.decrypt = decrypt;
+
+        DecodeStream.call(this);
     }
 
-    constructor.prototype = Stream.prototype;
+    const chunkSize = 512;
+
+    constructor.prototype = Object.create(DecodeStream.prototype);
+    constructor.prototype.readBlock = function() {
+      var chunk = this.str.getBytes(chunkSize);
+      if (!chunk || chunk.length == 0) {
+        this.eof = true;
+        return;
+      }
+      var decrypt = this.decrypt;
+      chunk = decrypt(chunk);
+
+      var bufferLength = this.bufferLength;
+      var i, n = chunk.length;
+      var buffer = this.ensureBuffer(bufferLength + n);
+      for (i = 0; i < n; i++)
+        buffer[bufferLength++] = chunk[i];
+      this.bufferLength = n;
+      this.eof = n < chunkSize;
+    };
 
     return constructor;
 })();
@@ -919,10 +950,10 @@ var Lexer = (function() {
 
     function ToHexDigit(ch) {
         if (ch >= "0" && ch <= "9")
-            return ch - "0";
-        ch = ch.toLowerCase();
-        if (ch >= "a" && ch <= "f")
-            return ch - "a";
+            return ch.charCodeAt(0) - 48;
+        ch = ch.toUpperCase();
+        if (ch >= "A" && ch <= "F")
+            return ch.charCodeAt(0) - 55;
         return -1;
     }
 
@@ -1216,7 +1247,7 @@ var Parser = (function() {
             // don't buffer inline image data
             this.buf2 = (this.inlineImg > 0) ? null : this.lexer.getObj();
         },
-        getObj: function() {
+        getObj: function(cipherTransform) {
             // refill buffer after inline image data
             if (this.inlineImg == 2)
                 this.refill();
@@ -1242,7 +1273,7 @@ var Parser = (function() {
                         this.shift();
                         if (IsEOF(this.buf1))
                             break;
-                        dict.set(key, this.getObj());
+                        dict.set(key, this.getObj(cipherTransform));
                     }
                 }
                 if (IsEOF(this.buf1))
@@ -1251,7 +1282,7 @@ var Parser = (function() {
                 // stream objects are not allowed inside content streams or
                 // object streams
                 if (this.allowStreams && IsCmd(this.buf2, "stream")) {
-                    return this.makeStream(dict);
+                    return this.makeStream(dict, cipherTransform);
                 } else {
                     this.shift();
                 }
@@ -1270,17 +1301,8 @@ var Parser = (function() {
             } else if (IsString(this.buf1)) { // string
                 var str = this.buf1;
                 this.shift();
-                if (this.fileKey) {
-                    var decrypt = new DecryptStream(new StringStream(str),
-                                                    this.fileKey,
-                                                    this.encAlgorithm,
-                                                    this.keyLength);
-                    var str = "";
-                    var pos = decrypt.pos;
-                    var length = decrypt.length;
-                    while (pos++ > length)
-                        str += decrypt.getChar();
-                }
+                if (cipherTransform)
+                    str = cipherTransform.decryptString(str);
                 return str;
             }
 
@@ -1289,7 +1311,7 @@ var Parser = (function() {
             this.shift();
             return obj;
         },
-        makeStream: function(dict) {
+        makeStream: function(dict, cipherTransform) {
             var lexer = this.lexer;
             var stream = lexer.stream;
 
@@ -1316,12 +1338,8 @@ var Parser = (function() {
             this.shift();
 
             stream = stream.makeSubStream(pos, length, dict);
-            if (this.fileKey) {
-                stream = new DecryptStream(stream,
-                                           this.fileKey,
-                                           this.encAlgorithm,
-                                           this.keyLength);
-            }
+            if (cipherTransform)
+                stream = cipherTransform.createString(stream);
             stream = this.filter(stream, dict, length);
             stream.parameters = dict;
             return stream;
@@ -1450,12 +1468,18 @@ var XRef = (function() {
         this.xrefstms = {};
         var trailerDict = this.readXRef(startXRef);
 
+        // prepare the XRef cache
+        this.cache = [];
+
+        var encrypt = trailerDict.get("Encrypt");
+        if (encrypt) {
+            var fileId = trailerDict.get("ID");
+            this.encrypt = new CipherTransformFactory(this.fetch(encrypt), fileId[0] /*, password */);
+        }
+
         // get the root dictionary (catalog) object
         if (!IsRef(this.root = trailerDict.get("Root")))
             error("Invalid root reference");
-
-        // prepare the XRef cache
-        this.cache = [];
     }
 
     constructor.prototype = {
@@ -1643,7 +1667,7 @@ var XRef = (function() {
                     }
                     error("bad XRef entry");
                 }
-                e = parser.getObj();
+                e = parser.getObj(this.encrypt);
                 // Don't cache streams since they are mutable.
                 if (!IsStream(e))
                     this.cache[num] = e;
@@ -2462,7 +2486,7 @@ var CanvasGraphics = (function() {
                             }
                         }
                     } else if (cmd == "Tf") { // eagerly collect all fonts
-                        var fontRes = resources.get("Font");
+                        var fontRes; // = resources.get("Font");
                         if (fontRes) {
                             fontRes = xref.fetchIfRef(fontRes);
                             var font = xref.fetchIfRef(fontRes.get(args[0].name));
diff --git a/security.js b/security.js
new file mode 100644 (file)
index 0000000..d6aa8d3
--- /dev/null
@@ -0,0 +1,261 @@
+/* -*- Mode: Java; tab-width: s; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
+/* vim: set shiftwidth=s tabstop=2 autoindent cindent expandtab: */
+
+"use strict";
+
+var ARCFourCipher = (function() {
+  function constructor(key) {
+    var key = this.key;
+    this.a = 0;
+    this.b = 0;
+    var s = new Uint8Array(256);
+    var i, j = 0, tmp, keyLength = key.length;
+    for (i = 0; i < 256; ++i)
+      s[i] = i;
+    for (i = 0; i < 256; ++i) {
+      tmp = s[i];
+      j = (j + tmp + key[i % keyLength]) & 0xFF;
+      s[i] = s[j];
+      s[j] = tmp;
+    }
+    this.s = s;
+  }
+
+  constructor.prototype = {
+    encryptBlock: function(data) {
+      var i, n = data.length, tmp, tmp2;
+      var a = this.a, b = this.b, s = this.s;
+      var output = new Uint8Array(n);
+      for (i = 0; i < n; ++i) {
+        var tmp;
+        a = (a + 1) & 0xFF;
+        tmp = s[a];
+        b = (b + tmp) & 0xFF;
+        tmp2 = s[b]
+        s[a] = tmp2;
+        s[b] = tmp;
+        output[i] = data[i] ^ s[(tmp + tmp2) & 0xFF];
+      }
+      this.a = a;
+      this.b = b;
+      return output;
+    }
+  };
+
+  return constructor;
+})();
+
+var md5 = (function() {
+  const r = new Uint8Array([
+    7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
+    5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,
+    4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
+    6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
+  const k = new Int32Array([
+    -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426,
+    -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162,
+    1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632,
+    643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438,
+    -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473,
+    -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060,
+    1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979,
+    76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415,
+    -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799,
+    1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379,
+    718787259, -343485551]);
+  
+  function hash(data, offset, length) {
+    var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
+    // pre-processing
+    var paddedLength = (length + 72) & ~63; // data + 9 extra bytes
+    var padded = new Uint8Array(paddedLength);
+    var i, j, n;
+    for (i = 0; i < length; ++i)
+      padded[i] = data[offset++];
+    padded[i++] = 0x80;
+    n = paddedLength - 8;
+    for (; i < n; ++i)
+      padded[i] = 0;
+    padded[i++] = (length << 3) & 0xFF;
+    padded[i++] = (length >> 5)  & 0xFF;
+    padded[i++] = (length >> 13)  & 0xFF;
+    padded[i++] = (length >> 21)  & 0xFF;
+    padded[i++] = (length >>> 29)  & 0xFF;
+    padded[i++] = 0;
+    padded[i++] = 0;
+    padded[i++] = 0;
+    // chunking
+    // TODO ArrayBuffer ?
+    var w = new Int32Array(16);
+    for (i = 0; i < paddedLength;) {
+      for (j = 0; j < 16; ++j, i += 4)
+        w[j] = padded[i] | (padded[i + 1] << 8) | (padded[i + 2] << 16) | (padded[i + 3] << 24);
+      var a = h0, b = h1, c = h2, d = h3, f, g;
+      for (j = 0; j < 64; ++j) {
+        if (j < 16) {
+          f = (b & c) | ((~b) & d);
+          g = j;
+        } else if (j < 32) {
+          f = (d & b) | ((~d) & c);
+          g = (5 * j + 1) & 15;
+        } else if (j < 48) {
+          f = b ^ c ^ d;
+          g = (3 * j + 5) & 15;
+        } else {
+          f = c ^ (b | (~d));
+          g = (7 * j) & 15;
+        }
+        var tmp = d, rotateArg = (a + f + k[j] + w[g]) | 0, rotate = r[j];
+        d = c;
+        c = b;
+        b = (b + ((rotateArg << rotate) | (rotateArg >>> (32 - rotate)))) | 0;
+        a = tmp;
+      }
+      h0 = (h0 + a) | 0;
+      h1 = (h1 + b) | 0;
+      h2 = (h2 + c) | 0;
+      h3 = (h3 + d) | 0;
+    }
+    return new Uint8Array([
+        h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,
+        h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,
+        h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,
+        h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF
+    ]);
+  }
+  return hash;
+})();
+
+var CipherTransform = (function() {
+  function constructor(stringCipherConstructor, streamCipherConstructor) {
+    this.stringCipherConstructor = stringCipherConstructor;
+    this.streamCipherConstructor = streamCipherConstructor;
+  }
+  constructor.prototype = {
+    createStream: function (stream) {
+      var cipher = new streamCipherConstructor();
+      return new DecryptStream(stream, function(data) {
+        return cipher.encryptBlock(data);
+      });
+    },
+    decryptString: function(s) {
+      var cipher = new stringCipherConstructor();
+      var data = string2bytes(s);
+      data = cipher.encryptBlock(data);
+      return bytes2string(data);
+    }
+  };
+  return constructor;
+})();
+
+var CipherTransformFactory = (function() {
+  function prepareKeyData(fileId, password, ownerPassword, userPassword, flags, revision, keyLength) {
+    const defaultPasswordBytes = new Uint8Array([
+      0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, 
+      0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
+    var hashData = new Uint8Array(88), i = 0, j, n;
+    if (password) {
+      n = Math.min(32, password.length);
+      for (; i < n; ++i)
+        hashData[i] = password[i];
+    }
+    j = 0;
+    while (i < 32) {
+      hashData[i++] = defaultPasswordBytes[j++];
+    }
+    // as now the padded password in the hashData[0..i]
+    for (j = 0, n = ownerPassword.length; j < n; ++j)
+      hashData[i++] = ownerPassword[j];
+    hashData[i++] = flags & 0xFF;
+    hashData[i++] = (flags >> 8) & 0xFF;
+    hashData[i++] = (flags >> 16) & 0xFF;
+    hashData[i++] = (flags >>> 24) & 0xFF;
+    for (j = 0, n = fileId.length; j < n; ++j)
+      hashData[i++] = fileId[j];
+    // TODO rev 4, if metadata is not encrypted pass 0xFFFFFF also
+    var hash = md5(hashData, 0, i);
+    var keyLengthInBytes = keyLength >> 3;
+    if (revision >= 3) {
+      for (j = 0; j < 50; ++j) {
+         hash = md5(hash, 0, keyLengthInBytes);
+      }
+    }
+    var encryptionKey = hash.subarray(0, keyLengthInBytes);
+    var cipher, checkData;
+
+    if (revision >= 3) {
+      // padded password in hashData, we can use this array for user password check
+      i = 32;
+      for(j = 0, n = fileId.length; j < n; ++j)
+        hashData[i++] = fileId[j];
+      cipher = new ARCFourCipher(encryptionKey);
+      var checkData = cipher.encryptBlock(md5(hashData, 0, i));
+      n = encryptionKey.length;
+      var derrivedKey = new Uint8Array(n), k;
+      for (j = 1; j <= 19; ++j) {
+        for (k = 0; k < n; ++k)
+          derrivedKey[k] = encryptionKey[k] ^ j;
+        cipher = new ARCFourCipher(derrivedKey);
+        checkData = cipher.encryptBlock(checkData);
+      }
+    } else {
+      cipher = new ARCFourCipher(encryptionKey);
+      checkData = cipher.encryptBlock(hashData.subarray(0, 32));
+    }
+    for (j = 0, n = checkData.length; j < n; ++j) {
+      if (userPassword[j] != checkData[j])
+        error("incorrect password");
+    }
+    return encryptionKey;
+  } 
+
+  function constructor(dict, fileId, password) {
+    var filter = dict.get("Filter");
+    if (!IsName(filter) || filter.name != "Standard")
+      error("unknown encryption method");
+    this.dict = dict;
+    var algorithm = dict.get("V");
+    if (!IsInt(algorithm) ||
+      (algorithm != 1 && algorithm != 2))
+      error("unsupported encryption algorithm");
+    // TODO support algorithm 4
+    var keyLength = dict.get("Length") || 40;
+    if (!IsInt(keyLength) ||
+      keyLength < 40 || (keyLength % 8) != 0)
+      error("invalid key length");
+    // prepare keys
+    var ownerPassword = stringToBytes(dict.get("O"));
+    var userPassword = stringToBytes(dict.get("U"));
+    var flags = dict.get("P");
+    var revision = dict.get("R");
+    var fileIdBytes = stringToBytes(fileId);
+    var passwordBytes;
+    if (password)
+      passwordBytes = stringToBytes(password);
+
+    this.encryptionKey = prepareKeyData(fileIdBytes, passwordBytes, 
+                                        ownerPassword, userPassword, flags, revision, keyLength);
+  }
+
+  constructor.prototype = {
+    createCipherTransform: function(num, gen) {
+      var encryptionKey = this.encryptionKey;
+      var key = new Uint8Array(encryptionKey.length + 5), i, j, n;
+      for (j = 0, n = encryptionKey.length; j < n; ++j)
+        key[j] = encryptionKey[j];
+      key[i++] = num & 0xFF;
+      key[i++] = (num >> 8) & 0xFF;
+      key[i++] = (num >> 16) & 0xFF;
+      key[i++] = gen & 0xFF;
+      key[i++] = (gen >> 8) & 0xFF;
+      var hash = md5(key, 0, i);
+      key = hash.subarray(0, Math.min(key.length, 16));
+      var cipherConstructor = function() {
+        return new ARCFourCipher(key);
+      };
+      return new CipherTransform(cipherConstructor, cipherConstructor);
+    }
+  };
+
+  return constructor;
+})();
index 6e733319eead4bdff8aac75b89bf0c94bd8978c3..4b9dd3cbda4c9aa0c899127e9607c52f6d66c805 100644 (file)
@@ -6,6 +6,7 @@
         <script type="text/javascript" src="viewer.js"></script>
         <script type="text/javascript" src="pdf.js"></script>
         <script type="text/javascript" src="fonts.js"></script>
+        <script type="text/javascript" src="security.js"></script>
         <script type="text/javascript" src="glyphlist.js"></script>
   </head>