Passed
Push — master ( fb0e87...bc1969 )
by Rutger
02:14
created

GnupgExtensionTrait::verifyViaGnupgExtension()   A

Complexity

Conditions 4
Paths 18

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.1755

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 28
ccs 14
cts 18
cp 0.7778
rs 9.6333
cc 4
nc 18
nop 2
crap 4.1755
1
<?php
2
3
namespace rhertogh\Yii2SecurityTxt\helpers\GPG\traits;
4
5
use gnupg;
6
use Yii;
7
use yii\base\InvalidConfigException;
8
use yii\helpers\FileHelper;
9
10
trait GnupgExtensionTrait
11
{
12
    /**
13
     * @throws InvalidConfigException
14
     */
15 2
    protected static function signViaGnupgExtension($message, $privateKey)
16
    {
17 2
        Yii::beginProfile('Generate PGP signature', __METHOD__);
18 2
        $gpg = static::getGnupg($gnupgHome);
19
        try {
20 2
            $gpg->seterrormode(GNUPG_ERROR_EXCEPTION);
21
22 2
            $keyInfo = $gpg->import($privateKey);
23 2
            if ($keyInfo === false) {
24
                throw new InvalidConfigException('Unable to import private key. Debug info: '
25
                    . var_export(static::generateGnupgDebugInfo($gpg), true));
26
            }
27 2
            $gpg->addsignkey($keyInfo['fingerprint']);
28
29 2
            $gpg->setsignmode(gnupg::SIG_MODE_CLEAR);
0 ignored issues
show
Bug introduced by
The constant gnupg::SIG_MODE_CLEAR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
30 2
            $output = $gpg->sign($message);
31
        } finally {
32 2
            FileHelper::removeDirectory($gnupgHome);
33
        }
34 2
        if ($output === false) {
35
            throw new InvalidConfigException('Unable to sign the message. Debug info: '
36
                . var_export(static::generateGnupgDebugInfo($gpg), true));
37
        }
38 2
        Yii::endProfile('Generate PGP signature', __METHOD__);
39 2
        return $output;
40
    }
41
42
    /**
43
     * @throws InvalidConfigException
44
     */
45 2
    protected static function verifyViaGnupgExtension($message, $publicKey)
46
    {
47 2
        Yii::beginProfile('Verify PGP signature', __METHOD__);
48 2
        $gpg = static::getGnupg($gnupgHome);
49
        try {
50 2
            $gpg->seterrormode(GNUPG_ERROR_EXCEPTION);
51
52 2
            $keyInfo = $gpg->import($publicKey);
53 2
            if ($keyInfo === false) {
54
                throw new InvalidConfigException('Unable to import public key. Debug info: '
55
                    . var_export(static::generateGnupgDebugInfo($gpg), true));
56
            }
57 2
            $gpg->addencryptkey($keyInfo['fingerprint']);
58 2
            $info = $gpg->verify($message,false,$plaintext);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $signature of gnupg::verify(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

58
            $info = $gpg->verify($message,/** @scrutinizer ignore-type */ false,$plaintext);
Loading history...
59
        } finally {
60 2
            FileHelper::removeDirectory($gnupgHome);
61
        }
62 2
        if ($info === false) {
63
            throw new InvalidConfigException('Unable to verify the message. Debug info: '
64
                . var_export(static::generateGnupgDebugInfo($gpg), true));
65
        }
66 2
        if ($info[0]['summary'] !== 0) {
67
            // Invalid signature
0 ignored issues
show
Coding Style introduced by
Inline comments must end in full-stops, exclamation marks, or question marks
Loading history...
68 2
            return false;
69
        }
70
71 2
        Yii::endProfile('Verify PGP signature', __METHOD__);
72 2
        return $plaintext;
73
    }
74
75
    protected static function generateGnupgDebugInfo(gnupg $gpg)
76
    {
77
        $debugInfo = [
78
            'engineInfo' => $gpg->getengineinfo(),
0 ignored issues
show
Bug introduced by
The method getengineinfo() does not exist on gnupg. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

78
            'engineInfo' => $gpg->/** @scrutinizer ignore-call */ getengineinfo(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
79
            'errorInfo' => $gpg->geterrorinfo(),
0 ignored issues
show
Bug introduced by
The method geterrorinfo() does not exist on gnupg. Did you maybe mean geterror()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

79
            'errorInfo' => $gpg->/** @scrutinizer ignore-call */ geterrorinfo(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
80
        ];
81
82
        if (!is_writable($debugInfo['engineInfo']['home_dir'])) {
83
            $debugInfo['hint'] = 'The gnupg home directory (' . $debugInfo['engineInfo']['home_dir'] . ') is not writable.';
84
        }
85
86
        return $debugInfo;
87
    }
88
89 3
    protected static function getGnupg(&$gnupgHome = null): gnupg
90
    {
91 3
        if (empty($gnupgHome)) {
92 3
            $gnupgHome = Yii::getAlias('@runtime') . '/gnupg/' . uniqid(more_entropy: true);
0 ignored issues
show
Bug introduced by
Are you sure Yii::getAlias('@runtime') of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
            $gnupgHome = /** @scrutinizer ignore-type */ Yii::getAlias('@runtime') . '/gnupg/' . uniqid(more_entropy: true);
Loading history...
93 3
            FileHelper::createDirectory($gnupgHome);
94
        }
95
96 3
        return new gnupg(['home_dir' => $gnupgHome]);
0 ignored issues
show
Unused Code introduced by
The call to gnupg::__construct() has too many arguments starting with array('home_dir' => $gnupgHome). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

96
        return /** @scrutinizer ignore-call */ new gnupg(['home_dir' => $gnupgHome]);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
97
    }
98
}
99