SecurityHandler.cc 12.5 KB
Newer Older
1 2 3 4 5 6 7 8
//========================================================================
//
// SecurityHandler.cc
//
// Copyright 2004 Glyph & Cog, LLC
//
//========================================================================

9 10 11 12 13 14 15
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
16
// Copyright (C) 2010, 2012, 2015, 2017, 2018 Albert Astals Cid <aacid@kde.org>
17
// Copyright (C) 2013 Adrian Johnson <ajohnson@redneon.com>
Fabio D'Urso's avatar
Fabio D'Urso committed
18
// Copyright (C) 2014 Fabio D'Urso <fabiodurso@hotmail.it>
19
// Copyright (C) 2016 Alok Anand <alok4nand@gmail.com>
20 21 22 23 24 25
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include "GooString.h"
#include "PDFDoc.h"
#include "Decrypt.h"
#include "Error.h"
#include "GlobalParams.h"
#ifdef ENABLE_PLUGINS
#  include "XpdfPluginAPI.h"
#endif
#include "SecurityHandler.h"

42 43
#include <limits.h>

44 45 46 47 48 49
//------------------------------------------------------------------------
// SecurityHandler
//------------------------------------------------------------------------

SecurityHandler *SecurityHandler::make(PDFDoc *docA, Object *encryptDictA) {
  SecurityHandler *secHdlr;
50
#ifdef ENABLE_PLUGINS
51
  XpdfSecurityHandler *xsh;
52
#endif
53

Albert Astals Cid's avatar
Albert Astals Cid committed
54
  Object filterObj = encryptDictA->dictLookup("Filter");
55 56 57 58 59 60 61 62
  if (filterObj.isName("Standard")) {
    secHdlr = new StandardSecurityHandler(docA, encryptDictA);
  } else if (filterObj.isName()) {
#ifdef ENABLE_PLUGINS
    if ((xsh = globalParams->getSecurityHandler(filterObj.getName()))) {
      secHdlr = new ExternalSecurityHandler(docA, encryptDictA, xsh);
    } else {
#endif
63
      error(errSyntaxError, -1, "Couldn't find the '{0:s}' security handler",
64
	    filterObj.getName());
65
      secHdlr = nullptr;
66 67 68 69
#ifdef ENABLE_PLUGINS
    }
#endif
  } else {
70
    error(errSyntaxError, -1,
71
	  "Missing or invalid 'Filter' entry in encryption dictionary");
72
    secHdlr = nullptr;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  }
  return secHdlr;
}

SecurityHandler::SecurityHandler(PDFDoc *docA) {
  doc = docA;
}

SecurityHandler::~SecurityHandler() {
}

GBool SecurityHandler::checkEncryption(GooString *ownerPassword,
				       GooString *userPassword) {
  void *authData;
  GBool ok;
  int i;

  if (ownerPassword || userPassword) {
    authData = makeAuthData(ownerPassword, userPassword);
  } else {
93
    authData = nullptr;
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  }
  ok = authorize(authData);
  if (authData) {
    freeAuthData(authData);
  }
  for (i = 0; !ok && i < 3; ++i) {
    if (!(authData = getAuthData())) {
      break;
    }
    ok = authorize(authData);
    if (authData) {
      freeAuthData(authData);
    }
  }
  if (!ok) {
109 110 111 112 113 114
    if (!ownerPassword && !userPassword) {
      GooString dummy;
      return checkEncryption(&dummy, &dummy);
    } else {
      error(errCommandLine, -1, "Incorrect password");
    }
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  }
  return ok;
}

//------------------------------------------------------------------------
// StandardSecurityHandler
//------------------------------------------------------------------------

class StandardAuthData {
public:

  StandardAuthData(GooString *ownerPasswordA, GooString *userPasswordA) {
    ownerPassword = ownerPasswordA;
    userPassword = userPasswordA;
  }

  ~StandardAuthData() {
    if (ownerPassword) {
      delete ownerPassword;
    }
    if (userPassword) {
      delete userPassword;
    }
  }

140 141 142
  StandardAuthData(const StandardAuthData &) = delete;
  StandardAuthData& operator=(const StandardAuthData &) = delete;

143 144 145 146 147 148 149 150 151
  GooString *ownerPassword;
  GooString *userPassword;
};

StandardSecurityHandler::StandardSecurityHandler(PDFDoc *docA,
						 Object *encryptDictA):
  SecurityHandler(docA)
{
  ok = gFalse;
152 153 154 155 156
  fileID = nullptr;
  ownerKey = nullptr;
  userKey = nullptr;
  ownerEnc = nullptr;
  userEnc = nullptr;
157
  fileKeyLength = 0;
158

Albert Astals Cid's avatar
Albert Astals Cid committed
159 160 161 162 163 164 165 166
  Object versionObj = encryptDictA->dictLookup("V");
  Object revisionObj = encryptDictA->dictLookup("R");
  Object lengthObj = encryptDictA->dictLookup("Length");
  Object ownerKeyObj = encryptDictA->dictLookup("O");
  Object userKeyObj = encryptDictA->dictLookup("U");
  Object ownerEncObj = encryptDictA->dictLookup("OE");
  Object userEncObj = encryptDictA->dictLookup("UE");
  Object permObj = encryptDictA->dictLookup("P");
Adrian Johnson's avatar
Adrian Johnson committed
167 168
  if (permObj.isInt64()) {
      unsigned int permUint = permObj.getInt64();
169
      int perms = permUint - UINT_MAX - 1;
Albert Astals Cid's avatar
Albert Astals Cid committed
170
      permObj = Object(perms);
171
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
172
  Object fileIDObj = doc->getXRef()->getTrailerDict()->dictLookup("ID");
173 174
  if (versionObj.isInt() &&
      revisionObj.isInt() &&
175 176 177
      permObj.isInt() &&
      ownerKeyObj.isString() &&
      userKeyObj.isString()) {
178 179
    encVersion = versionObj.getInt();
    encRevision = revisionObj.getInt();
180 181 182
    if ((encRevision <= 4 &&
	 ownerKeyObj.getString()->getLength() == 32 &&
	 userKeyObj.getString()->getLength() == 32) ||
183
	((encRevision == 5 || encRevision == 6) &&
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
	 // the spec says 48 bytes, but Acrobat pads them out longer
	 ownerKeyObj.getString()->getLength() >= 48 &&
	 userKeyObj.getString()->getLength() >= 48 &&
	 ownerEncObj.isString() &&
	 ownerEncObj.getString()->getLength() == 32 &&
	 userEncObj.isString() &&
	 userEncObj.getString()->getLength() == 32)) {
      encAlgorithm = cryptRC4;
      // revision 2 forces a 40-bit key - some buggy PDF generators
      // set the Length value incorrectly
      if (encRevision == 2 || !lengthObj.isInt()) {
	fileKeyLength = 5;
      } else {
	fileKeyLength = lengthObj.getInt() / 8;
      }
      encryptMetadata = gTrue;
      //~ this currently only handles a subset of crypt filter functionality
      //~ (in particular, it ignores the EFF entry in encryptDictA, and
      //~ doesn't handle the case where StmF, StrF, and EFF are not all the
      //~ same)
      if ((encVersion == 4 || encVersion == 5) &&
205
	  (encRevision == 4 || encRevision == 5 || encRevision == 6)) {
Albert Astals Cid's avatar
Albert Astals Cid committed
206 207 208
	Object cryptFiltersObj = encryptDictA->dictLookup("CF");
	Object streamFilterObj = encryptDictA->dictLookup("StmF");
	Object stringFilterObj = encryptDictA->dictLookup("StrF");
209 210 211 212 213 214 215 216
	if (cryptFiltersObj.isDict() &&
	    streamFilterObj.isName() &&
	    stringFilterObj.isName() &&
	    !strcmp(streamFilterObj.getName(), stringFilterObj.getName())) {
	  if (!strcmp(streamFilterObj.getName(), "Identity")) {
	    // no encryption on streams or strings
	    encVersion = encRevision = -1;
	  } else {
Albert Astals Cid's avatar
Albert Astals Cid committed
217 218 219
	    Object cryptFilterObj = cryptFiltersObj.dictLookup(streamFilterObj.getName());
	    if (cryptFilterObj.isDict()) {
	      Object cfmObj = cryptFilterObj.dictLookup("CFM");
220 221 222
	      if (cfmObj.isName("V2")) {
		encVersion = 2;
		encRevision = 3;
Albert Astals Cid's avatar
Albert Astals Cid committed
223 224
		Object cfLengthObj = cryptFilterObj.dictLookup("Length");
		if (cfLengthObj.isInt()) {
225 226 227 228 229 230 231
		  //~ according to the spec, this should be cfLengthObj / 8
		  fileKeyLength = cfLengthObj.getInt();
		}
	      } else if (cfmObj.isName("AESV2")) {
		encVersion = 2;
		encRevision = 3;
		encAlgorithm = cryptAES;
Albert Astals Cid's avatar
Albert Astals Cid committed
232 233
		Object cfLengthObj = cryptFilterObj.dictLookup("Length");
		if (cfLengthObj.isInt()) {
234 235 236 237 238
		  //~ according to the spec, this should be cfLengthObj / 8
		  fileKeyLength = cfLengthObj.getInt();
		}
	      } else if (cfmObj.isName("AESV3")) {
		encVersion = 5;
239
		// let encRevision be 5 or 6
240
		encAlgorithm = cryptAES256;
Albert Astals Cid's avatar
Albert Astals Cid committed
241 242
		Object cfLengthObj = cryptFilterObj.dictLookup("Length");
		if (cfLengthObj.isInt()) {
243 244 245 246
		  //~ according to the spec, this should be cfLengthObj / 8
		  fileKeyLength = cfLengthObj.getInt();
		}
	      }
247 248 249
	    }
	  }
	}
Albert Astals Cid's avatar
Albert Astals Cid committed
250 251
	Object encryptMetadataObj = encryptDictA->dictLookup("EncryptMetadata");
	if (encryptMetadataObj.isBool()) {
252 253
	  encryptMetadata = encryptMetadataObj.getBool();
	}
254
      }
255 256 257 258 259 260
      permFlags = permObj.getInt();
      ownerKey = ownerKeyObj.getString()->copy();
      userKey = userKeyObj.getString()->copy();
      if (encVersion >= 1 && encVersion <= 2 &&
	  encRevision >= 2 && encRevision <= 3) {
	if (fileIDObj.isArray()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
261 262
	  Object fileIDObj1 = fileIDObj.arrayGet(0);
	  if (fileIDObj1.isString()) {
263
	    fileID = fileIDObj1.getString()->copy();
264 265 266
	  } else {
	    fileID = new GooString();
	  }
267 268 269
	} else {
	  fileID = new GooString();
	}
270 271 272 273
	if (fileKeyLength > 16 || fileKeyLength < 0) {
	  fileKeyLength = 16;
	}
	ok = gTrue;
274
      } else if (encVersion == 5 && (encRevision == 5 || encRevision == 6)) {
275
	fileID = new GooString(); // unused for V=R=5
276 277 278 279 280 281 282 283 284
	if (ownerEncObj.isString() && userEncObj.isString()) {
	  ownerEnc = ownerEncObj.getString()->copy();
	  userEnc = userEncObj.getString()->copy();
	  if (fileKeyLength > 32 || fileKeyLength < 0) {
	    fileKeyLength = 32;
	  }
	  ok = gTrue;
	} else {
	  error(errSyntaxError, -1, "Weird encryption owner/user info");
285 286
	}
      } else if (!(encVersion == -1 && encRevision == -1)) {
287
	error(errUnimplemented, -1,
Fabio D'Urso's avatar
Fabio D'Urso committed
288
	      "Unsupported version/revision ({0:d}/{1:d}) of Standard security handler",
289
	      encVersion, encRevision);
290 291
      }
    } else {
292
      error(errSyntaxError, -1, "Invalid encryption key length");
293 294
    }
  } else {
295
    error(errSyntaxError, -1, "Weird encryption info");
296 297 298 299 300 301 302 303 304 305 306 307 308
  }
}

StandardSecurityHandler::~StandardSecurityHandler() {
  if (fileID) {
    delete fileID;
  }
  if (ownerKey) {
    delete ownerKey;
  }
  if (userKey) {
    delete userKey;
  }
309 310 311 312 313 314 315 316 317
  if (ownerEnc) {
    delete ownerEnc;
  }
  if (userEnc) {
    delete userEnc;
  }
}

GBool StandardSecurityHandler::isUnencrypted() {
318 319 320
  if (!ok) {
    return gTrue;
  }
321
  return encVersion == -1 && encRevision == -1;
322 323 324 325 326
}

void *StandardSecurityHandler::makeAuthData(GooString *ownerPassword,
					    GooString *userPassword) {
  return new StandardAuthData(ownerPassword ? ownerPassword->copy()
327
			                    : (GooString *)nullptr,
328
			      userPassword ? userPassword->copy()
329
			                   : (GooString *)nullptr);
330 331 332
}

void *StandardSecurityHandler::getAuthData() {
333
  return nullptr;
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
}

void StandardSecurityHandler::freeAuthData(void *authData) {
  delete (StandardAuthData *)authData;
}

GBool StandardSecurityHandler::authorize(void *authData) {
  GooString *ownerPassword, *userPassword;

  if (!ok) {
    return gFalse;
  }
  if (authData) {
    ownerPassword = ((StandardAuthData *)authData)->ownerPassword;
    userPassword = ((StandardAuthData *)authData)->userPassword;
  } else {
350 351
    ownerPassword = nullptr;
    userPassword = nullptr;
352 353
  }
  if (!Decrypt::makeFileKey(encVersion, encRevision, fileKeyLength,
354 355
			    ownerKey, userKey, ownerEnc, userEnc,
			    permFlags, fileID,
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
			    ownerPassword, userPassword, fileKey,
			    encryptMetadata, &ownerPasswordOk)) {
    return gFalse;
  }
  return gTrue;
}

#ifdef ENABLE_PLUGINS

//------------------------------------------------------------------------
// ExternalSecurityHandler
//------------------------------------------------------------------------

ExternalSecurityHandler::ExternalSecurityHandler(PDFDoc *docA,
						 Object *encryptDictA,
						 XpdfSecurityHandler *xshA):
  SecurityHandler(docA)
{
  encryptDictA->copy(&encryptDict);
  xsh = xshA;
376
  encAlgorithm = cryptRC4; //~ this should be obtained via getKey
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
  ok = gFalse;

  if (!(*xsh->newDoc)(xsh->handlerData, (XpdfDoc)docA,
		      (XpdfObject)encryptDictA, &docData)) {
    return;
  }

  ok = gTrue;
}

ExternalSecurityHandler::~ExternalSecurityHandler() {
  (*xsh->freeDoc)(xsh->handlerData, docData);
}

void *ExternalSecurityHandler::makeAuthData(GooString *ownerPassword,
					    GooString *userPassword) {
  char *opw, *upw;
  void *authData;

  opw = ownerPassword ? ownerPassword->getCString() : (char *)NULL;
  upw = userPassword ? userPassword->getCString() : (char *)NULL;
  if (!(*xsh->makeAuthData)(xsh->handlerData, docData, opw, upw, &authData)) {
    return NULL;
  }
  return authData;
}

void *ExternalSecurityHandler::getAuthData() {
  void *authData;

  if (!(*xsh->getAuthData)(xsh->handlerData, docData, &authData)) {
    return NULL;
  }
  return authData;
}

void ExternalSecurityHandler::freeAuthData(void *authData) {
  (*xsh->freeAuthData)(xsh->handlerData, docData, authData);
}

GBool ExternalSecurityHandler::authorize(void *authData) {
  char *key;
  int length;

  if (!ok) {
    return gFalse;
  }
  permFlags = (*xsh->authorize)(xsh->handlerData, docData, authData);
  if (!(permFlags & xpdfPermissionOpen)) {
    return gFalse;
  }
428
  if (!(*xsh->getKey)(xsh->handlerData, docData, &key, &length, &encVersion, &encRevision)) {
429 430 431 432 433 434 435 436 437 438 439
    return gFalse;
  }
  if ((fileKeyLength = length) > 16) {
    fileKeyLength = 16;
  }
  memcpy(fileKey, key, fileKeyLength);
  (*xsh->freeKey)(xsh->handlerData, docData, key, length);
  return gTrue;
}

#endif // ENABLE_PLUGINS