Completed
Pull Request — master (#1917)
by Lukas
40:33 queued 30:26
created

browserSupportsCspV3()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 16
rs 9.4285
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Lukas Reschke <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OC\Security\CSP;
23
24
use OC\Security\CSRF\CsrfTokenManager;
25
use OCP\IRequest;
26
27
/**
28
 * @package OC\Security\CSP
29
 */
30
class ContentSecurityPolicyNonceManager {
31
	/** @var CsrfTokenManager */
32
	private $csrfTokenManager;
33
	/** @var IRequest */
34
	private $request;
35
	/** @var string */
36
	private $nonce = '';
37
38
	/**
39
	 * @param CsrfTokenManager $csrfTokenManager
40
	 * @param IRequest $request
41
	 */
42
	public function __construct(CsrfTokenManager $csrfTokenManager,
43
								IRequest $request) {
44
		$this->csrfTokenManager = $csrfTokenManager;
45
		$this->request = $request;
46
	}
47
48
	/**
49
	 * Returns the current CSP nounce
50
	 *
51
	 * @return string
52
	 */
53
	public function getNonce() {
54
		if($this->nonce === '') {
55
			$this->nonce = base64_encode($this->csrfTokenManager->getToken()->getEncryptedValue());
56
		}
57
58
		return $this->nonce;
59
	}
60
61
	/**
62
	 * Check if the browser supports CSP v3
63
	 *
64
	 * @return bool
65
	 */
66
	public function browserSupportsCspV3() {
67
		$browserWhitelist = [
68
			// Chrome 40+
69
			'/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[4-9][0-9].[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/',
70
			// Firefox 45+
71
			'/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/(4[5-9]|[5-9][0-9])\.[0-9.]+$/',
72
			// Safari 10+
73
			'/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/1[0-9.]+ Safari\/[0-9.A-Z]+$/',
74
		];
75
76
		if($this->request->isUserAgent($browserWhitelist)) {
77
			return true;
78
		}
79
80
		return false;
81
	}
82
}
83