PinEntry.php 21.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Contains a class implementing automatic pinentry for gpg-agent
 *
 * LICENSE:
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see
 * <http://www.gnu.org/licenses/>
 *
 * @category  Encryption
 * @package   Crypt_GPG
 * @author    Michael Gauthier <mike@silverorange.com>
 * @copyright 2013 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @link      http://pear.php.net/package/Crypt_GPG
 */

/**
 * CLI user-interface and parser.
 */
require_once 'Console/CommandLine.php';

/**
 * A command-line dummy pinentry program for use with gpg-agent and Crypt_GPG
 *
 * This pinentry receives passphrases through en environment variable and
 * automatically enters the PIN in response to gpg-agent requests. No user-
 * interaction required.
 *
 * The pinentry can be run independently for testing and debugging with the
 * following syntax:
 *
 * <pre>
 * Usage:
 *   crypt-gpg-pinentry [options]
 *
 * Options:
 *   -l log, --log=log  Optional location to log pinentry activity.
 *   -v, --verbose      Sets verbosity level. Use multiples for more detail
 *                      (e.g. "-vv").
 *   -h, --help         show this help message and exit
 *   --version          show the program version and exit
 * </pre>
 *
 * @category  Encryption
 * @package   Crypt_GPG
 * @author    Michael Gauthier <mike@silverorange.com>
 * @copyright 2013 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @link      http://pear.php.net/package/Crypt_GPG
 * @see       Crypt_GPG::getKeys()
 */
class Crypt_GPG_PinEntry
{
    /**
     * Verbosity level for showing no output.
     */
    const VERBOSITY_NONE = 0;

    /**
     * Verbosity level for showing error output.
     */
    const VERBOSITY_ERRORS = 1;

    /**
     * Verbosity level for showing all output, including Assuan protocol
     * messages.
     */
    const VERBOSITY_ALL = 2;

    /**
     * Length of buffer for reading lines from the Assuan server.
     *
     * PHP reads 8192 bytes. If this is set to less than 8192, PHP reads 8192
     * and buffers the rest so we might as well just read 8192.
     *
     * Using values other than 8192 also triggers PHP bugs.
     *
     * @see http://bugs.php.net/bug.php?id=35224
     */
    const CHUNK_SIZE = 8192;

    /**
     * File handle for the input stream
     *
     * @var resource
     */
    protected $stdin = null;

    /**
     * File handle for the output stream
     *
     * @var resource
     */
    protected $stdout = null;

    /**
     * File handle for the log file if a log file is used
     *
     * @var resource
     */
    protected $logFile = null;

    /**
     * Whether or not this pinentry is finished and is exiting
     *
     * @var boolean
     */
    protected $moribund = false;

    /**
     * Verbosity level
     *
     * One of:
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_NONE},
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_ERRORS}, or
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_ALL}
     *
     * @var integer
     */
    protected $verbosity = self::VERBOSITY_NONE;

    /**
     * The command-line interface parser for this pinentry
     *
     * @var Console_CommandLine
     *
     * @see Crypt_GPG_PinEntry::getParser()
     */
    protected $parser = null;

    /**
     * PINs to be entered by this pinentry
     *
     * An indexed array of associative arrays in the form:
     * <code>
     * <?php
     *   array(
     *     array(
     *       'keyId'      => $keyId,
     *       'passphrase' => $passphrase
     *     ),
     *     ...
     *   );
     * ?>
     * </code>
     *
     * This array is parsed from the environment variable
     * <kbd>PINENTRY_USER_DATA</kbd>.
     *
     * @var array
     *
     * @see Crypt_GPG_PinEntry::initPinsFromENV()
     */
    protected $pins = array();

    /**
     * The PIN currently being requested by the Assuan server
     *
     * If set, this is an associative array in the form:
     * <code>
     * <?php
     *   array(
     *     'keyId'  => $shortKeyId,
     *     'userId' => $userIdString
     *   );
     * ?>
     * </code>
     *
     * @var array|null
     */
    protected $currentPin = null;

    /**
     * Runs this pinentry
     *
     * @return void
     */
    public function __invoke()
    {
        $this->parser = $this->getCommandLineParser();

        try {
            $result = $this->parser->parse();

            $this->setVerbosity($result->options['verbose']);
            $this->setLogFilename($result->options['log']);

            $this->connect();
            $this->initPinsFromENV();

            while (($line = fgets($this->stdin, self::CHUNK_SIZE)) !== false) {
                $this->parseCommand(mb_substr($line, 0, -1, '8bit'));
                if ($this->moribund) {
                    break;
                }
            }

            $this->disconnect();

        } catch (Console_CommandLineException $e) {
            $this->log($e->getMessage() . PHP_EOL, slf::VERBOSITY_ERRORS);
            exit(1);
        } catch (Exception $e) {
            $this->log($e->getMessage() . PHP_EOL, self::VERBOSITY_ERRORS);
            $this->log($e->getTraceAsString() . PHP_EOL, self::VERBOSITY_ERRORS);
            exit(1);
        }
    }

    /**
     * Sets the verbosity of logging for this pinentry
     *
     * Verbosity levels are:
     *
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_NONE}   - no logging.
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_ERRORS} - log errors only.
     * - {@link Crypt_GPG_PinEntry::VERBOSITY_ALL}    - log everything, including
     *                                                  the assuan protocol.
     *
     * @param integer $verbosity the level of verbosity of this pinentry.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    public function setVerbosity($verbosity)
    {
        $this->verbosity = (integer)$verbosity;
        return $this;
    }

    /**
     * Sets the log file location
     *
     * @param string $filename the new log filename to use. If an empty string
     *                         is used, file-based logging is disabled.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    public function setLogFilename($filename)
    {
        if (is_resource($this->logFile)) {
            fflush($this->logFile);
            fclose($this->logFile);
            $this->logFile = null;
        }

        if ($filename != '') {
            if (($this->logFile = fopen($filename, 'w')) === false) {
                $this->log(
                    'Unable to open log file "' . $filename . '" '
                    . 'for writing.' . PHP_EOL,
                    self::VERBOSITY_ERRORS
                );
                exit(1);
            } else {
                stream_set_write_buffer($this->logFile, 0);
            }
        }

        return $this;
    }

    /**
     * Gets the CLI user-interface definition for this pinentry
     *
     * Detects whether or not this package is PEAR-installed and appropriately
     * locates the XML UI definition.
     *
     * @return string the location of the CLI user-interface definition XML.
     */
    protected function getUIXML()
    {
        // Find PinEntry config depending on the way how the package is installed
        $ds    = DIRECTORY_SEPARATOR;
        $root  = __DIR__ . $ds . '..' . $ds . '..' . $ds;
        $paths = array(
            '@data-dir@' . $ds . '@package-name@' . $ds . 'data', // PEAR
            $root . 'data', // Git
            $root . 'data' . $ds . 'Crypt_GPG' . $ds . 'data', // Composer
        );

        foreach ($paths as $path) {
            if (file_exists($path . $ds . 'pinentry-cli.xml')) {
                return $path . $ds . 'pinentry-cli.xml';
            }
        }
    }

    /**
     * Gets the CLI parser for this pinentry
     *
     * @return Console_CommandLine the CLI parser for this pinentry.
     */
    protected function getCommandLineParser()
    {
        return Console_CommandLine::fromXmlFile($this->getUIXML());
    }

    /**
     * Logs a message at the specified verbosity level
     *
     * If a log file is used, the message is written to the log. Otherwise,
     * the message is sent to STDERR.
     *
     * @param string  $data  the message to log.
     * @param integer $level the verbosity level above which the message should
     *                       be logged.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function log($data, $level)
    {
        if ($this->verbosity >= $level) {
            if (is_resource($this->logFile)) {
                fwrite($this->logFile, $data);
                fflush($this->logFile);
            } else {
                $this->parser->outputter->stderr($data);
            }
        }

        return $this;
    }

    /**
     * Connects this pinentry to the assuan server
     *
     * Opens I/O streams and sends initial handshake.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function connect()
    {
        // Binary operations will not work on Windows with PHP < 5.2.6.
        $rb = (version_compare(PHP_VERSION, '5.2.6') < 0) ? 'r' : 'rb';
        $wb = (version_compare(PHP_VERSION, '5.2.6') < 0) ? 'w' : 'wb';

        $this->stdin  = fopen('php://stdin', $rb);
        $this->stdout = fopen('php://stdout', $wb);

        if (function_exists('stream_set_read_buffer')) {
            stream_set_read_buffer($this->stdin, 0);
        }
        stream_set_write_buffer($this->stdout, 0);

        // initial handshake
        $this->send($this->getOK('Crypt_GPG pinentry ready and waiting'));

        return $this;
    }

    /**
     * Parses an assuan command and performs the appropriate action
     *
     * Documentation of the assuan commands for pinentry is limited to
     * non-existent. Most of these commands were taken from the C source code
     * to gpg-agent and pinentry.
     *
     * Additional context was provided by using strace -f when calling the
     * gpg-agent.
     *
     * @param string $line the assuan command line to parse
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function parseCommand($line)
    {
        $this->log('<- ' . $line . PHP_EOL, self::VERBOSITY_ALL);

        $parts = explode(' ', $line, 2);

        $command = $parts[0];

        if (count($parts) === 2) {
            $data = $parts[1];
        } else {
            $data = null;
        }

        switch ($command) {
        case 'SETDESC':
            return $this->sendSetDescription($data);

        case 'MESSAGE':
            return $this->sendMessage();

        case 'CONFIRM':
            return $this->sendConfirm();

        case 'GETINFO':
            return $this->sendGetInfo($data);

        case 'GETPIN':
            return $this->sendGetPin($data);

        case 'RESET':
            return $this->sendReset();

        case 'BYE':
            return $this->sendBye();

        default:
            return $this->sendNotImplementedOK();
        }
    }

    /**
     * Initializes the PINs to be entered by this pinentry from the environment
     * variable PINENTRY_USER_DATA
     *
     * The PINs are parsed from a JSON-encoded string.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function initPinsFromENV()
    {
        if (($userData = getenv('PINENTRY_USER_DATA')) !== false) {
            $pins = json_decode($userData, true);
            if ($pins === null) {
                $this->log(
                    '-- failed to parse user data' . PHP_EOL,
                    self::VERBOSITY_ERRORS
                );
            } else {
                $this->pins = $pins;
                $this->log(
                    '-- got user data [not showing passphrases]' . PHP_EOL,
                    self::VERBOSITY_ALL
                );
            }
        }

        return $this;
    }

    /**
     * Disconnects this pinentry from the Assuan server
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function disconnect()
    {
        $this->log('-- disconnecting' . PHP_EOL, self::VERBOSITY_ALL);

        fflush($this->stdout);
        fclose($this->stdout);
        fclose($this->stdin);

        $this->stdin  = null;
        $this->stdout = null;

        $this->log('-- disconnected' . PHP_EOL, self::VERBOSITY_ALL);

        if (is_resource($this->logFile)) {
            fflush($this->logFile);
            fclose($this->logFile);
            $this->logFile = null;
        }

        return $this;
    }

    /**
     * Sends an OK response for a not implemented feature
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendNotImplementedOK()
    {
        return $this->send($this->getOK());
    }

    /**
     * Parses the currently requested key identifier and user identifier from
     * the description passed to this pinentry
     *
     * @param string $text the raw description sent from gpg-agent.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendSetDescription($text)
    {
        $text = rawurldecode($text);
        $matches = array();
        // TODO: handle user id with quotation marks
        $exp = '/\n"(.+)"\n.*\sID ([A-Z0-9]+),\n/mu';
        if (preg_match($exp, $text, $matches) === 1) {
            $userId = $matches[1];
            $keyId  = $matches[2];

            if ($this->currentPin === null || $this->currentPin['keyId'] !== $keyId) {
                $this->currentPin = array(
                    'userId' => $userId,
                    'keyId'  => $keyId
                );
                $this->log(
                    '-- looking for PIN for ' . $keyId . PHP_EOL,
                    self::VERBOSITY_ALL
                );
            }
        }

        return $this->send($this->getOK());
    }

    /**
     * Tells the assuan server to confirm the operation
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendConfirm()
    {
        return $this->send($this->getOK());
    }

    /**
     * Tells the assuan server that any requested pop-up messages were confirmed
     * by pressing the fake 'close' button
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendMessage()
    {
        return $this->sendButtonInfo('close');
    }

    /**
     * Sends information about pressed buttons to the assuan server
     *
     * This is used to fake a user-interface for this pinentry.
     *
     * @param string $text the button status to send.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendButtonInfo($text)
    {
        return $this->send('BUTTON_INFO ' . $text . "\n");
    }

    /**
     * Sends the PIN value for the currently requested key
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendGetPin()
    {
        $foundPin = '';

        if (is_array($this->currentPin)) {
            $keyIdLength = mb_strlen($this->currentPin['keyId'], '8bit');

            // search for the pin
            foreach ($this->pins as $_keyId => $pin) {
                // Warning: GnuPG 2.1 asks 3 times for passphrase if it is invalid
                $keyId        = $this->currentPin['keyId'];
                $_keyIdLength = mb_strlen($_keyId, '8bit');

                // Get last X characters of key identifier to compare
                // Most GnuPG versions use 8 characters, but recent ones can use 16,
                // We support 8 for backward compatibility
                if ($keyIdLength < $_keyIdLength) {
                    $_keyId = mb_substr($_keyId, -$keyIdLength, $keyIdLength, '8bit');
                } else if ($keyIdLength > $_keyIdLength) {
                    $keyId = mb_substr($keyId, -$_keyIdLength, $_keyIdLength, '8bit');
                }

                if ($_keyId === $keyId) {
                    $foundPin = $pin;
                    break;
                }
            }
        }

        return $this
            ->send($this->getData($foundPin))
            ->send($this->getOK());
    }

    /**
     * Sends information about this pinentry
     *
     * @param string $data the information requested by the assuan server.
     *                     Currently only 'pid' is supported. Other requests
     *                     return no information.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendGetInfo($data)
    {
        $parts   = explode(' ', $data, 2);
        $command = reset($parts);

        switch ($command) {
        case 'pid':
            return $this->sendGetInfoPID();
        default:
            return $this->send($this->getOK());
        }

        return $this;
    }

    /**
     * Sends the PID of this pinentry to the assuan server
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendGetInfoPID()
    {
        return $this
            ->send($this->getData(getmypid()))
            ->send($this->getOK());
    }

    /**
     * Flags this pinentry for disconnection and sends an OK response
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendBye()
    {
        $return = $this->send($this->getOK('closing connection'));
        $this->moribund = true;
        return $return;
    }

    /**
     * Resets this pinentry and sends an OK response
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function sendReset()
    {
        $this->currentPin = null;
        return $this->send($this->getOK());
    }

    /**
     * Gets an OK response to send to the assuan server
     *
     * @param string $data an optional message to include with the OK response.
     *
     * @return string the OK response.
     */
    protected function getOK($data = null)
    {
        $return = 'OK';

        if ($data) {
            $return .= ' ' . $data;
        }

        return $return . "\n";
    }

    /**
     * Gets data ready to send to the assuan server
     *
     * Data is appropriately escaped and long lines are wrapped.
     *
     * @param string $data the data to send to the assuan server.
     *
     * @return string the properly escaped, formatted data.
     *
     * @see http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
     */
    protected function getData($data)
    {
        // Escape data. Only %, \n and \r need to be escaped but other
        // values are allowed to be escaped. See
        // http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
        $data = rawurlencode($data);
        $data = $this->getWordWrappedData($data, 'D');
        return $data;
    }

    /**
     * Gets a comment ready to send to the assuan server
     *
     * @param string $data the comment to send to the assuan server.
     *
     * @return string the properly formatted comment.
     *
     * @see http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
     */
    protected function getComment($data)
    {
        return $this->getWordWrappedData($data, '#');
    }

    /**
     * Wraps strings at 1,000 bytes without splitting UTF-8 multibyte
     * characters
     *
     * Each line is prepended with the specified line prefix. Wrapped lines
     * are automatically appended with \ characters.
     *
     * Protocol strings are UTF-8 but maximum line length is 1,000 bytes.
     * <kbd>mb_strcut()</kbd> is used so we can limit line length by bytes
     * and not split characters across multiple lines.
     *
     * @param string $data   the data to wrap.
     * @param string $prefix a single character to use as the line prefix. For
     *                       example, 'D' or '#'.
     *
     * @return string the word-wrapped, prefixed string.
     *
     * @see http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html
     */
    protected function getWordWrappedData($data, $prefix)
    {
        $lines = array();

        do {
            if (mb_strlen($data, '8bit') > 997) {
                $line = $prefix . ' ' . mb_strcut($data, 0, 996, 'utf-8') . "\\\n";
                $lines[] = $line;
                $lineLength = mb_strlen($line, '8bit') - 1;
                $dataLength = mb_substr($data, '8bit');
                $data = mb_substr(
                    $data,
                    $lineLength,
                    $dataLength - $lineLength,
                    '8bit'
                );
            } else {
                $lines[] = $prefix . ' ' . $data . "\n";
                $data = '';
            }
        } while ($data != '');

        return implode('', $lines);
    }

    /**
     * Sends raw data to the assuan server
     *
     * @param string $data the data to send.
     *
     * @return Crypt_GPG_PinEntry the current object, for fluent interface.
     */
    protected function send($data)
    {
        $this->log('-> ' . $data, self::VERBOSITY_ALL);
        fwrite($this->stdout, $data);
        fflush($this->stdout);
        return $this;
    }
}