public function validateApiAccessControl() { if (kIpAddressUtils::isInternalIp()) { return true; } if ($this->getEnforceHttpsApi() && infraRequestUtils::getProtocol() != infraRequestUtils::PROTOCOL_HTTPS) { KalturaLog::err('Action was accessed over HTTP while the partner is configured for HTTPS access only'); return false; } $accessControl = $this->getApiAccessControl(); if (is_null($accessControl)) { return true; } $context = new kEntryContextDataResult(); $scope = new accessControlScope(); $scope->setKs(kCurrentContext::$ks); $scope->setContexts(array(ContextType::PLAY)); $disableCache = $accessControl->applyContext($context, $scope); if ($disableCache) { kApiCache::disableCache(); } if (count($context->getMessages())) { header("X-Kaltura-API-Access-Control: " . implode(', ', $context->getMessages())); } if (count($context->getActions())) { $actions = $context->getActions(); foreach ($actions as $action) { /* @var $action kAccessControlAction */ if ($action->getType() == RuleActionType::BLOCK) { KalturaLog::err('Action was blocked by API access control'); return false; } } } return true; }
/** * Return true if the current request's ip matches the saved ips list * @return bool */ protected function matchIpAddress() { $accessControlScope = $this->getAccessControlScope(); $requestIp = $accessControlScope->getIp(); foreach ($this->ipAddressList as $checkIp) { if (kIpAddressUtils::isIpInRange($requestIp, $checkIp)) { return true; } } return false; }
protected function matches($field, $value) { return kIpAddressUtils::isIpInRange($field, $value); }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $fileName = $this->getRequestParameter("fileName"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $pathOnly = $this->getRequestParameter("pathOnly", false); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if ($fileName) { header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Type: application/force-download"); header("Content-Description: File Transfer"); } $clipTo = null; $entry = $flavorAsset->getentry(); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($entry, $flavorAsset); $version = $this->getRequestParameter("v"); if (!$version) { $version = $flavorAsset->getVersion(); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) { $path = null; list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false); if ($file_sync) { $parent_file_sync = kFileSyncUtils::resolve($file_sync); $path = $parent_file_sync->getFullPath(); if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; } } $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO); } // milliseconds if ($clipTo == 0) { $clipTo = self::NO_CLIP_TO; } if (!is_numeric($clipTo) || $clipTo < 0) { KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number'); } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFileUtils::dumpFile($path, null, null); KExternalErrors::dieGracefully(); } else { if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) { $limit_file_size = 0; if ($clipTo != self::NO_CLIP_TO) { if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) { $contentPath = myContentStorage::getFSContentRootPath(); $tempClipName = $version . '_' . $clipTo . '.mp4'; $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName); if (!file_exists($tempClipPath)) { kFile::fullMkdir($tempClipPath); $clipToSec = round($clipTo / 1000, 3); $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1"; KalturaLog::log("Executing {$cmdLine}"); $output = array(); $return_value = ""; exec($cmdLine, $output, $return_value); KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output)); } if (file_exists($tempClipPath)) { KalturaLog::log("Dumping {$tempClipPath}"); kFileUtils::dumpFile($tempClipPath); } else { KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping'); } } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2); } } $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size); if (!$fileName) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); KExternalErrors::dieGracefully(); }
protected function isAnonymous($ks) { if (kIpAddressUtils::isInternalIp()) { return false; } if (!$ks || !$ks->isAdmin() && ($ks->user === "0" || $ks->user === null)) { return true; } if (kConf::hasParam('cache_anonymous_users')) { $anonymousUsers = kConf::get('cache_anonymous_users'); foreach ($anonymousUsers as $userName => $partnerIds) { if ($ks->user == $userName && in_array($ks->partner_id, explode(',', $partnerIds))) { return true; } } } return false; }
function checkCache() { $baseDir = "/tmp/cache_v2"; $start_time = microtime(true); $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https" : "http"; $host = ""; if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { $host = $_SERVER['HTTP_X_FORWARDED_HOST']; } else { if (isset($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } } $uri = $_SERVER["REQUEST_URI"]; if (function_exists('apc_fetch')) { $url = apc_fetch("redirect-" . $protocol . $uri); if ($url) { sendCachingHeaders(60, true, time()); header("X-Kaltura:cached-dispatcher-redirect"); header("Location:{$url}"); die; } $errorHeaders = apc_fetch("exterror-{$protocol}://{$host}{$uri}"); if ($errorHeaders !== false) { sendCachingHeaders(60, true, time()); foreach ($errorHeaders as $header) { header($header); } die; } } if (strpos($uri, "/playManifest") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kPlayManifestCacher.php"; $cache = kPlayManifestCacher::getInstance(); $cache->checkOrStart(); } else { if (strpos($uri, "/partnerservices2") !== false) { $params = $_GET + $_POST; unset($params['ks']); unset($params['kalsig']); $params['uri'] = $_SERVER['PATH_INFO']; $params['__protocol'] = $protocol; ksort($params); $keys = array_keys($params); $key = md5(implode("|", $params) . implode("|", $keys)); $cache_filename = "{$baseDir}/cache-{$key}"; if (file_exists($cache_filename)) { if (filemtime($cache_filename) + 600 < time()) { @unlink($cache_filename); @unlink($cache_filename . ".headers"); @unlink($cache_filename . ".log"); } else { $content_type = @file_get_contents("{$baseDir}/cache-{$key}.headers"); if ($content_type) { header("Content-Type: {$content_type}"); } $response = @file_get_contents("{$baseDir}/cache-{$key}"); if ($response) { header("Access-Control-Allow-Origin:*"); // avoid html5 xss issues if (strpos($uri, "/partnerservices2/executeplaylist") !== false) { $max_age = 60; sendCachingHeaders($max_age, true, time()); } else { sendCachingHeaders(0); } $processing_time = microtime(true) - $start_time; header("X-Kaltura:cached-dispatcher,{$key},{$processing_time}"); echo $response; die; } } } } else { if (strpos($uri, "/kwidget") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { // check if we cached the patched swf with flashvars $uri = $protocol . $uri; $cachedResponse = $cache->get("kwidgetswf{$uri}"); if ($cachedResponse) { $max_age = 60 * 10; header("X-Kaltura:cached-dispatcher"); header("Content-Type: application/x-shockwave-flash"); sendCachingHeaders($max_age, true, time()); header("Content-Length: " . strlen($cachedResponse)); echo $cachedResponse; die; } $cachedResponse = $cache->get("kwidget{$uri}"); if ($cachedResponse) { header("X-Kaltura:cached-dispatcher"); header("Expires: Sun, 19 Nov 2000 08:52:00 GMT"); header("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); header("Pragma", "no-cache"); if (strpos($uri, "nowrapper") !== false) { header("Location:{$cachedResponse}"); die; } $referer = @$_SERVER['HTTP_REFERER']; $externalInterfaceDisabled = strstr($referer, "bebo.com") === false && strstr($referer, "myspace.com") === false && strstr($referer, "current.com") === false && strstr($referer, "myyearbook.com") === false && strstr($referer, "facebook.com") === false && strstr($referer, "friendster.com") === false ? "" : "&externalInterfaceDisabled=1"; $noncached_params = $externalInterfaceDisabled . "&referer=" . urlencode($referer); if (strpos($cachedResponse, "/swfparams/") > 0) { $cachedResponse = substr($cachedResponse, 0, -4) . urlencode($noncached_params) . ".swf"; } else { $cachedResponse .= $noncached_params; } header("Location:{$cachedResponse}"); die; } } } else { if (strpos($uri, "/thumbnail") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php'; $cachedResponse = $cache->get("thumb{$uri}"); if ($cachedResponse && is_array($cachedResponse)) { list($renderer, $invalidationKey, $cacheTime) = $cachedResponse; $keysStore = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_QUERY_CACHE_KEYS); if ($keysStore) { $modifiedTime = $keysStore->get($invalidationKey); if ($modifiedTime && $modifiedTime > $cacheTime) { return; // entry has changed (not necessarily the thumbnail) } } require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php'; KalturaMonitorClient::initApiMonitor(true, 'extwidget.thumbnail', $renderer->partnerId); header("X-Kaltura:cached-dispatcher-thumb"); $renderer->output(); die; } } } else { if (strpos($uri, "/embedIframe/") !== false) { require_once dirname(__FILE__) . "/../apps/kaltura/lib/cache/kCacheManager.php"; $cache = kCacheManager::getSingleLayerCache(kCacheManager::CACHE_TYPE_PS2); if ($cache) { // check if we cached the patched swf with flashvars $cachedResponse = $cache->get("embedIframe{$uri}"); if ($cachedResponse) { header("X-Kaltura:cached-dispatcher"); sendCachingHeaders(0); header("Location:{$cachedResponse}"); die; } } } else { if (strpos($uri, "/serveFlavor/") !== false && function_exists('apc_fetch') && $_SERVER["REQUEST_METHOD"] == "GET") { require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererDumpFile.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/renderers/kRendererString.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/monitor/KalturaMonitorClient.php'; require_once dirname(__FILE__) . '/../apps/kaltura/lib/request/kIpAddressUtils.php'; $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST']; $cacheKey = 'dumpFile-' . kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR']) . '-' . $host . $uri; $renderer = apc_fetch($cacheKey); if ($renderer) { KalturaMonitorClient::initApiMonitor(true, 'extwidget.serveFlavor', $renderer->partnerId); header("X-Kaltura:cached-dispatcher"); $renderer->output(); die; } } } } } } } }
protected function applyCondition($fieldValue, $condition, $refValue) { switch ($condition) { case self::COND_MATCH: if (!count($refValue)) { return null; } return in_array($fieldValue, $refValue); case self::COND_REGEX: if (!count($refValue)) { return null; } foreach ($refValue as $curRefValue) { if ($fieldValue === $curRefValue || preg_match("/{$curRefValue}/i", $fieldValue)) { return true; } } return false; case self::COND_SITE_MATCH: if (!count($refValue)) { return null; } foreach ($refValue as $curRefValue) { if ($fieldValue === $curRefValue || strpos($fieldValue, "." . $curRefValue) !== false) { return true; } } return false; case self::COND_IP_RANGE: if (!count($refValue)) { return null; } require_once dirname(__FILE__) . '/../../infra/utils/kIpAddressUtils.php'; foreach ($refValue as $curRefValue) { if (kIpAddressUtils::isIpInRange($fieldValue, $curRefValue)) { return true; } } return false; } return $fieldValue; }
/** * Init with allowed permissions for the user in the given KS or kCurrentContext if not KS given * kCurrentContext::init should have been executed before! * @param string $ks KS to extract user and partner IDs from instead of kCurrentContext * @param boolean $useCache use cache or not * @throws TODO: add all exceptions */ public static function init($useCache = null) { $securityContext = array(kCurrentContext::$partner_id, kCurrentContext::$ks); if ($securityContext === self::$lastInitializedContext) { KalturaLog::log('Already initalized for this security context'); self::$cacheWatcher->apply(); return; } // verify that kCurrentContext::init has been executed since it must be used to init current context permissions if (!kCurrentContext::$ksPartnerUserInitialized) { KalturaLog::crit('kCurrentContext::initKsPartnerUser must be executed before initializing kPermissionManager'); throw new Exception('kCurrentContext has not been initialized!', null); } // can be initialized more than once to support multirequest with different kCurrentContext parameters self::$lastInitializedContext = null; self::$cacheWatcher = new kApiCacheWatcher(); self::$useCache = $useCache ? true : false; // copy kCurrentContext parameters (kCurrentContext::init should have been executed before) self::$requestedPartnerId = !self::isEmpty(kCurrentContext::$partner_id) ? kCurrentContext::$partner_id : null; self::$ksPartnerId = !self::isEmpty(kCurrentContext::$ks_partner_id) ? kCurrentContext::$ks_partner_id : null; if (self::$ksPartnerId == Partner::ADMIN_CONSOLE_PARTNER_ID && kConf::hasParam('admin_console_partner_allowed_ips')) { $ipAllowed = false; $ipRanges = explode(',', kConf::get('admin_console_partner_allowed_ips')); foreach ($ipRanges as $curRange) { if (kIpAddressUtils::isIpInRange($_SERVER['REMOTE_ADDR'], $curRange)) { $ipAllowed = true; break; } } if (!$ipAllowed) { throw new kCoreException("Admin console partner used from an unallowed address", kCoreException::PARTNER_BLOCKED); } } self::$ksUserId = !self::isEmpty(kCurrentContext::$ks_uid) ? kCurrentContext::$ks_uid : null; if (self::$ksPartnerId != Partner::BATCH_PARTNER_ID) { self::$kuser = !self::isEmpty(kCurrentContext::getCurrentKsKuser()) ? kCurrentContext::getCurrentKsKuser() : null; } self::$ksString = kCurrentContext::$ks ? kCurrentContext::$ks : null; self::$adminSession = !self::isEmpty(kCurrentContext::$is_admin_session) ? kCurrentContext::$is_admin_session : false; // if ks defined - check that it is valid self::errorIfKsNotValid(); // init partner, user, and role objects self::initPartnerUserObjects(); // throw an error if KS partner (operating partner) is blocked self::errorIfPartnerBlocked(); //throw an error if KS user is blocked self::errorIfUserBlocked(); // init role ids self::initRoleIds(); // init permissions map self::initPermissionsMap(); // initialization done self::$lastInitializedContext = $securityContext; self::$cacheWatcher->stop(); return true; }