PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.15.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.15.0
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / Nonce.php
matomo / app / core Last commit date
API 2 years ago Access 3 years ago Application 4 years ago Archive 3 years ago ArchiveProcessor 2 years ago Archiver 5 years ago AssetManager 3 years ago Auth 3 years ago Category 5 years ago Changes 3 years ago CliMulti 4 years ago Columns 3 years ago Concurrency 3 years ago Config 4 years ago Container 4 years ago CronArchive 3 years ago DataAccess 2 years ago DataFiles 5 years ago DataTable 2 years ago Db 3 years ago DeviceDetector 3 years ago Email 5 years ago Exception 3 years ago Http 4 years ago Intl 4 years ago Mail 3 years ago Measurable 5 years ago Menu 3 years ago Metrics 4 years ago Notification 4 years ago Period 4 years ago Plugin 2 years ago ProfessionalServices 4 years ago Report 5 years ago ReportRenderer 2 years ago Scheduler 4 years ago Segment 3 years ago Session 4 years ago Settings 3 years ago Tracker 3 years ago Translation 4 years ago UpdateCheck 5 years ago Updater 3 years ago Updates 3 years ago Validators 4 years ago View 4 years ago ViewDataTable 3 years ago Visualization 4 years ago Widget 5 years ago Access.php 4 years ago Archive.php 3 years ago ArchiveProcessor.php 2 years ago AssetManager.php 4 years ago Auth.php 5 years ago AuthResult.php 5 years ago BaseFactory.php 5 years ago Cache.php 5 years ago CacheId.php 5 years ago CliMulti.php 4 years ago Common.php 3 years ago Config.php 3 years ago Console.php 3 years ago Context.php 5 years ago Cookie.php 3 years ago CronArchive.php 3 years ago DataArray.php 4 years ago DataTable.php 2 years ago Date.php 3 years ago Db.php 4 years ago DbHelper.php 3 years ago Development.php 5 years ago ErrorHandler.php 5 years ago EventDispatcher.php 3 years ago ExceptionHandler.php 3 years ago FileIntegrity.php 3 years ago Filechecks.php 4 years ago Filesystem.php 3 years ago FrontController.php 3 years ago Http.php 3 years ago IP.php 4 years ago Log.php 4 years ago LogDeleter.php 4 years ago Mail.php 3 years ago Metrics.php 3 years ago NoAccessException.php 5 years ago Nonce.php 3 years ago Notification.php 5 years ago NumberFormatter.php 4 years ago Option.php 4 years ago Period.php 5 years ago Piwik.php 3 years ago Plugin.php 4 years ago Profiler.php 4 years ago ProxyHeaders.php 5 years ago ProxyHttp.php 3 years ago QuickForm2.php 5 years ago RankingQuery.php 3 years ago ReportRenderer.php 4 years ago Segment.php 3 years ago Sequence.php 5 years ago Session.php 3 years ago SettingsPiwik.php 3 years ago SettingsServer.php 5 years ago Singleton.php 5 years ago Site.php 3 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 3 years ago TCPDF.php 5 years ago Theme.php 5 years ago Timer.php 5 years ago Tracker.php 4 years ago Twig.php 4 years ago Unzip.php 5 years ago UpdateCheck.php 5 years ago Updater.php 4 years ago UpdaterErrorException.php 5 years ago Updates.php 5 years ago Url.php 2 years ago UrlHelper.php 3 years ago Version.php 2 years ago View.php 3 years ago bootstrap.php 3 years ago dispatch.php 5 years ago testMinimumPhpVersion.php 3 years ago
Nonce.php
247 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9 namespace Piwik;
10
11 use Piwik\Session\SessionNamespace;
12
13 /**
14 * Nonce class.
15 *
16 * A cryptographic nonce -- "number used only once" -- is often recommended as
17 * part of a robust defense against cross-site request forgery (CSRF/XSRF). This
18 * class provides static methods that create and manage nonce values.
19 *
20 * Nonces in Piwik are stored as a session variable and have a configurable expiration.
21 *
22 * Learn more about nonces [here](http://en.wikipedia.org/wiki/Cryptographic_nonce).
23 *
24 * @api
25 */
26 class Nonce
27 {
28 /**
29 * Returns an existing nonce by ID. If none exists, a new nonce will be generated.
30 *
31 * @param string $id Unique id to avoid namespace conflicts, e.g., `'ModuleName.ActionName'`.
32 * @param int $ttl Optional time-to-live in seconds; default is 5 minutes. (ie, in 5 minutes,
33 * the nonce will no longer be valid).
34 * @return string
35 */
36 public static function getNonce($id, $ttl = 600)
37 {
38 // save session-dependent nonce
39 $ns = new SessionNamespace($id);
40 $nonce = $ns->nonce;
41
42 // re-use an unexpired nonce (a small deviation from the "used only once" principle, so long as we do not reset the expiration)
43 // to handle browser pre-fetch or double fetch caused by some browser add-ons/extensions
44 if (empty($nonce)) {
45 // generate a new nonce
46 $nonce = md5(SettingsPiwik::getSalt() . time() . Common::generateUniqId());
47 $ns->nonce = $nonce;
48 }
49
50 // extend lifetime if nonce is requested again to prevent from early timeout if nonce is requested again
51 // a few seconds before timeout
52 $ns->setExpirationSeconds($ttl, 'nonce');
53
54 return $nonce;
55 }
56
57 /**
58 * Returns if a nonce is valid and comes from a valid request.
59 *
60 * A nonce is valid if it matches the current nonce and if the current nonce
61 * has not expired.
62 *
63 * The request is valid if the referrer is a local URL (see {@link Url::isLocalUrl()})
64 * and if the HTTP origin is valid (see {@link getAcceptableOrigins()}).
65 *
66 * @param string $id The nonce's unique ID. See {@link getNonce()}.
67 * @param string $cnonce Nonce sent from client.
68 * @param null|string $allowedReferrerHost The allowed referrer host for the HTTP referrer URL.
69 * @return bool `true` if valid; `false` otherwise.
70 */
71 public static function verifyNonce($id, $cnonce, $allowedReferrerHost = null)
72 {
73 // load error with message function.
74 $error = self::verifyNonceWithErrorMessage($id, $cnonce, $allowedReferrerHost);
75 return $error === "";
76 }
77
78 /**
79 * Returns an error message, if any of the individual checks fails.
80 *
81 * A nonce must match the current nonce and must not be expired.
82 *
83 * If a referrer is present, it must match $allowedReferrerHost. The exception is a referrer that resolves to local,
84 * which is allowed if $allowedReferrerHost is empty.
85 * If a referrer is not present, then $allowedReferrerHost is ignored.
86 *
87 * The HTTP origin must be valid (see {@link getAcceptableOrigins()}).
88 *
89 * @param string $id The nonce's unique ID. See {@link getNonce()}.
90 * @param string $cnonce Nonce sent from client.
91 * @param string|null $allowedReferrerHost The allowed referrer for the HTTP referrer URL. See method description.
92 * @return string if empty is valid otherwise return error message
93 */
94 public static function verifyNonceWithErrorMessage($id, $cnonce, $allowedReferrerHost = null)
95 {
96 $ns = new SessionNamespace($id);
97 $nonce = $ns->nonce;
98
99 $additionalErrors = '';
100
101 // The Session cookie is set to a secure cookie, when SSL is mis-configured, it can cause the PHP session cookie ID to change on each page view.
102 // Indicate to user how to solve this particular use case by forcing secure connections.
103 if (Url::isSecureConnectionAssumedByPiwikButNotForcedYet()) {
104 $additionalErrors = '<br/><br/>' . Piwik::translate('Login_InvalidNonceSSLMisconfigured',
105 array(
106 '<a target="_blank" rel="noreferrer noopener" href="https://matomo.org/faq/how-to/faq_91/">',
107 '</a>',
108 'config/config.ini.php',
109 '<pre>force_ssl=1</pre>',
110 '<pre>[General]</pre>',
111 )
112 );
113 }
114
115 // validate token
116 if (empty($cnonce) || $cnonce !== $nonce) {
117 return Piwik::translate('Login_InvalidNonceToken');
118 }
119
120 // Validate referrer if present
121 $referrer = Url::getReferrer();
122 if (!empty($referrer)) {
123 // Allow the instance host by default, if no allowedReferrerHost is specified.
124 if (empty($allowedReferrerHost) && !Url::isLocalUrl($referrer)) {
125 return Piwik::translate('Login_InvalidNonceReferrer', array(
126 '<a target="_blank" rel="noreferrer noopener" href="https://matomo.org/faq/how-to-install/faq_98">',
127 '</a>'
128 )) . $additionalErrors;
129 }
130
131 // Test that referrer matches what is allowed.
132 if (!empty($allowedReferrerHost) && !self::isReferrerHostValid($referrer, $allowedReferrerHost)) {
133 return Piwik::translate('Login_InvalidNonceUnexpectedReferrer') . $additionalErrors;
134 }
135 }
136
137 // validate origin
138 $origin = self::getOrigin();
139 if (!empty($origin) &&
140 ($origin == 'null'
141 || !in_array($origin, self::getAcceptableOrigins()))
142 ) {
143 return Piwik::translate('Login_InvalidNonceOrigin') . $additionalErrors;
144 }
145
146 return '';
147 }
148
149 // public for tests
150 public static function isReferrerHostValid($referrer, $allowedReferrerHost)
151 {
152 if (empty($referrer)) {
153 return false;
154 }
155
156 $referrerHost = Url::getHostFromUrl($referrer);
157 return preg_match('/(^|\.)' . preg_quote($allowedReferrerHost) . '$/i', $referrerHost);
158 }
159
160 /**
161 * Force expiration of the current nonce.
162 *
163 * @param string $id The unique nonce ID.
164 */
165 public static function discardNonce($id)
166 {
167 $ns = new SessionNamespace($id);
168 $ns->unsetAll();
169 }
170
171 /**
172 * Returns the **Origin** HTTP header or `false` if not found.
173 *
174 * @return string|bool
175 */
176 public static function getOrigin()
177 {
178 if (!empty($_SERVER['HTTP_ORIGIN'])) {
179 return $_SERVER['HTTP_ORIGIN'];
180 }
181 return false;
182 }
183
184 /**
185 * Returns a list acceptable values for the HTTP **Origin** header.
186 *
187 * @return array
188 */
189 public static function getAcceptableOrigins()
190 {
191 $host = Url::getCurrentHost(null);
192
193 if (empty($host)) {
194 return array();
195 }
196
197 // parse host:port
198 if (preg_match('/^([^:]+):([0-9]+)$/D', $host, $matches)) {
199 $host = $matches[1];
200 $port = $matches[2];
201 $origins = array(
202 'http://' . $host,
203 'https://' . $host,
204 );
205 if ($port != 443) {
206 $origins[] = 'http://' . $host .':' . $port;
207 }
208 $origins[] = 'https://' . $host . ':' . $port;
209 } elseif (Config::getInstance()->General['force_ssl']) {
210 $origins = array(
211 'https://' . $host,
212 'https://' . $host . ':443',
213 );
214 } else {
215 $origins = array(
216 'http://' . $host,
217 'https://' . $host,
218 'http://' . $host . ':80',
219 'https://' . $host . ':443',
220 );
221 }
222
223 return $origins;
224 }
225
226 /**
227 * Verifies and discards a nonce.
228 *
229 * @param string $nonceName The nonce's unique ID. See {@link getNonce()}.
230 * @param string|null $nonce The nonce from the client. If `null`, the value from the
231 * **nonce** query parameter is used.
232 * @throws \Exception if the nonce is invalid. See {@link verifyNonce()}.
233 */
234 public static function checkNonce($nonceName, $nonce = null, $allowedReferrerHost = null)
235 {
236 if ($nonce === null) {
237 $nonce = Common::getRequestVar('nonce', null, 'string');
238 }
239
240 if (!self::verifyNonce($nonceName, $nonce, $allowedReferrerHost)) {
241 throw new \Exception(Piwik::translate('General_ExceptionSecurityCheckFailed'));
242 }
243
244 self::discardNonce($nonceName);
245 }
246 }
247