API
5 years ago
Access
5 years ago
Application
5 years ago
Archive
5 years ago
ArchiveProcessor
5 years ago
Archiver
5 years ago
AssetManager
5 years ago
Auth
5 years ago
Category
5 years ago
CliMulti
5 years ago
Columns
5 years ago
Composer
5 years ago
Concurrency
5 years ago
Config
5 years ago
Container
5 years ago
CronArchive
5 years ago
DataAccess
5 years ago
DataFiles
5 years ago
DataTable
5 years ago
Db
5 years ago
DeviceDetector
5 years ago
Email
5 years ago
Exception
5 years ago
Http
5 years ago
Intl
5 years ago
Mail
5 years ago
Measurable
5 years ago
Menu
5 years ago
Metrics
5 years ago
Notification
5 years ago
Period
5 years ago
Plugin
5 years ago
ProfessionalServices
5 years ago
Report
5 years ago
ReportRenderer
5 years ago
Scheduler
5 years ago
Segment
5 years ago
Session
5 years ago
Settings
5 years ago
Tracker
5 years ago
Translation
5 years ago
UpdateCheck
5 years ago
Updater
5 years ago
Updates
5 years ago
Validators
5 years ago
View
5 years ago
ViewDataTable
5 years ago
Visualization
5 years ago
Widget
5 years ago
.htaccess
6 years ago
Access.php
5 years ago
Archive.php
5 years ago
ArchiveProcessor.php
5 years ago
AssetManager.php
5 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
5 years ago
Common.php
5 years ago
Config.php
5 years ago
Console.php
5 years ago
Context.php
5 years ago
Cookie.php
5 years ago
CronArchive.php
5 years ago
DataArray.php
5 years ago
DataTable.php
5 years ago
Date.php
5 years ago
Db.php
5 years ago
DbHelper.php
5 years ago
Development.php
5 years ago
ErrorHandler.php
5 years ago
EventDispatcher.php
5 years ago
ExceptionHandler.php
5 years ago
FileIntegrity.php
5 years ago
Filechecks.php
5 years ago
Filesystem.php
5 years ago
FrontController.php
5 years ago
Http.php
5 years ago
IP.php
5 years ago
Log.php
5 years ago
LogDeleter.php
5 years ago
Mail.php
5 years ago
Metrics.php
5 years ago
NoAccessException.php
5 years ago
Nonce.php
5 years ago
Notification.php
5 years ago
NumberFormatter.php
5 years ago
Option.php
5 years ago
Period.php
5 years ago
Piwik.php
5 years ago
Plugin.php
5 years ago
Profiler.php
5 years ago
ProxyHeaders.php
5 years ago
ProxyHttp.php
5 years ago
QuickForm2.php
5 years ago
RankingQuery.php
5 years ago
ReportRenderer.php
5 years ago
Segment.php
5 years ago
Sequence.php
5 years ago
Session.php
5 years ago
SettingsPiwik.php
5 years ago
SettingsServer.php
5 years ago
Singleton.php
5 years ago
Site.php
5 years ago
SupportedBrowser.php
5 years ago
TCPDF.php
5 years ago
Theme.php
5 years ago
Timer.php
5 years ago
Tracker.php
5 years ago
Twig.php
5 years ago
Unzip.php
5 years ago
UpdateCheck.php
5 years ago
Updater.php
5 years ago
UpdaterErrorException.php
5 years ago
Updates.php
5 years ago
Url.php
5 years ago
UrlHelper.php
5 years ago
Version.php
5 years ago
View.php
5 years ago
bootstrap.php
5 years ago
dispatch.php
5 years ago
testMinimumPhpVersion.php
5 years ago
Nonce.php
200 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 string $expectedReferrerHost The expected referrer host for the HTTP referrer URL. |
| 69 | * @return bool `true` if valid; `false` otherwise. |
| 70 | */ |
| 71 | public static function verifyNonce($id, $cnonce, $expectedReferrerHost = null) |
| 72 | { |
| 73 | $ns = new SessionNamespace($id); |
| 74 | $nonce = $ns->nonce; |
| 75 | |
| 76 | // validate token |
| 77 | if (empty($cnonce) || $cnonce !== $nonce) { |
| 78 | return false; |
| 79 | } |
| 80 | |
| 81 | // validate referrer |
| 82 | $referrer = Url::getReferrer(); |
| 83 | if (empty($expectedReferrerHost) && !empty($referrer) && !Url::isLocalUrl($referrer)) { |
| 84 | return false; |
| 85 | } |
| 86 | if (!empty($expectedReferrerHost) && !self::isReferrerHostValid($referrer, $expectedReferrerHost)) { |
| 87 | return false; |
| 88 | } |
| 89 | |
| 90 | // validate origin |
| 91 | $origin = self::getOrigin(); |
| 92 | if (!empty($origin) && |
| 93 | ($origin == 'null' |
| 94 | || !in_array($origin, self::getAcceptableOrigins())) |
| 95 | ) { |
| 96 | return false; |
| 97 | } |
| 98 | |
| 99 | return true; |
| 100 | } |
| 101 | |
| 102 | // public for tests |
| 103 | public static function isReferrerHostValid($referrer, $expectedReferrerHost) |
| 104 | { |
| 105 | if (empty($referrer)) { |
| 106 | return false; |
| 107 | } |
| 108 | |
| 109 | $referrerHost = Url::getHostFromUrl($referrer); |
| 110 | return preg_match('/(^|\.)' . preg_quote($expectedReferrerHost) . '$/i', $referrerHost); |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Force expiration of the current nonce. |
| 115 | * |
| 116 | * @param string $id The unique nonce ID. |
| 117 | */ |
| 118 | public static function discardNonce($id) |
| 119 | { |
| 120 | $ns = new SessionNamespace($id); |
| 121 | $ns->unsetAll(); |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Returns the **Origin** HTTP header or `false` if not found. |
| 126 | * |
| 127 | * @return string|bool |
| 128 | */ |
| 129 | public static function getOrigin() |
| 130 | { |
| 131 | if (!empty($_SERVER['HTTP_ORIGIN'])) { |
| 132 | return $_SERVER['HTTP_ORIGIN']; |
| 133 | } |
| 134 | return false; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Returns a list acceptable values for the HTTP **Origin** header. |
| 139 | * |
| 140 | * @return array |
| 141 | */ |
| 142 | public static function getAcceptableOrigins() |
| 143 | { |
| 144 | $host = Url::getCurrentHost(null); |
| 145 | |
| 146 | if (empty($host)) { |
| 147 | return array(); |
| 148 | } |
| 149 | |
| 150 | // parse host:port |
| 151 | if (preg_match('/^([^:]+):([0-9]+)$/D', $host, $matches)) { |
| 152 | $host = $matches[1]; |
| 153 | $port = $matches[2]; |
| 154 | $origins = array( |
| 155 | 'http://' . $host, |
| 156 | 'https://' . $host, |
| 157 | ); |
| 158 | if ($port != 443) { |
| 159 | $origins[] = 'http://' . $host .':' . $port; |
| 160 | } |
| 161 | $origins[] = 'https://' . $host . ':' . $port; |
| 162 | } elseif (Config::getInstance()->General['force_ssl']) { |
| 163 | $origins = array( |
| 164 | 'https://' . $host, |
| 165 | 'https://' . $host . ':443', |
| 166 | ); |
| 167 | } else { |
| 168 | $origins = array( |
| 169 | 'http://' . $host, |
| 170 | 'https://' . $host, |
| 171 | 'http://' . $host . ':80', |
| 172 | 'https://' . $host . ':443', |
| 173 | ); |
| 174 | } |
| 175 | |
| 176 | return $origins; |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Verifies and discards a nonce. |
| 181 | * |
| 182 | * @param string $nonceName The nonce's unique ID. See {@link getNonce()}. |
| 183 | * @param string|null $nonce The nonce from the client. If `null`, the value from the |
| 184 | * **nonce** query parameter is used. |
| 185 | * @throws \Exception if the nonce is invalid. See {@link verifyNonce()}. |
| 186 | */ |
| 187 | public static function checkNonce($nonceName, $nonce = null, $expectedReferrerHost = null) |
| 188 | { |
| 189 | if ($nonce === null) { |
| 190 | $nonce = Common::getRequestVar('nonce', null, 'string'); |
| 191 | } |
| 192 | |
| 193 | if (!self::verifyNonce($nonceName, $nonce, $expectedReferrerHost)) { |
| 194 | throw new \Exception(Piwik::translate('General_ExceptionNonceMismatch')); |
| 195 | } |
| 196 | |
| 197 | self::discardNonce($nonceName); |
| 198 | } |
| 199 | } |
| 200 |