private function getSshKeygenValue($args, $tmpFileContents, $readTmpFile = false) { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $filePath = CACHEPATH . "/_tmp." . CryptoTool::hash($tmpFileContents); if (!$readTmpFile) { @file_put_contents($filePath, $tmpFileContents); @chmod($filePath, 0600); } $pipes = array(); $process = @proc_open("ssh-keygen -f {$filePath} {$args}", $descriptorspec, $pipes); if (@is_resource($process)) { @fclose($pipes[0]); $retval = trim(stream_get_contents($pipes[1])); fclose($pipes[1]); fclose($pipes[2]); } if ($readTmpFile) { $retval = file_get_contents($filePath); } @unlink($filePath); return $retval; }
/** * Set special cookies. We could re-create session based on that cookies. */ public static function keepSession() { $session = self::getInstance(); $tm = strtotime(Scalr::config('scalr.security.user.session.cookie_lifetime')); $setHttpsCookie = filter_has_var(INPUT_SERVER, 'HTTPS'); $signature = self::createCookieHash($session->userId, $tm, $session->sault, $session->hash); $token = CryptoTool::hash("{$signature}:" . $session->hashpwd); setcookie('scalr_user_id', $session->userId, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_sault', $session->sault, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_hash', $session->hash, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_expire', $tm, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_signature', $signature, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_token', $token, $tm, "/", null, $setHttpsCookie, false); $session->setToken($token); }
public function save() { $container = \Scalr::getContainer(); if (!$this->ID) { $this->ID = 0; $this->Hash = substr(CryptoTool::hash(uniqid(rand(), true)), 0, 14); if (!$this->ClientID && $container->initialized('environment')) { $this->ClientID = $container->environment->clientId; } if (!$this->EnvID && $container->initialized('environment')) { $this->EnvID = $container->environment->id; } } if ($this->DB->GetOne("\n SELECT id FROM farms\n WHERE name = ?\n AND env_id = ?\n AND id != ?\n LIMIT 1\n ", array($this->Name, $this->EnvID, $this->ID))) { throw new Exception(sprintf('The name "%s" is already used.', $this->Name)); } if (!$this->ID) { $this->DB->Execute("\n INSERT INTO farms\n SET status = ?,\n name = ?,\n clientid = ?,\n env_id = ?,\n hash = ?,\n created_by_id = ?,\n created_by_email = ?,\n changed_by_id = ?,\n changed_time = ?,\n dtadded = NOW(),\n farm_roles_launch_order = ?,\n comments = ?\n ", array(FARM_STATUS::TERMINATED, $this->Name, $this->ClientID, $this->EnvID, $this->Hash, $this->ownerId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->RolesLaunchOrder, $this->Comments)); $this->ID = $this->DB->Insert_ID(); } else { $this->DB->Execute("\n UPDATE farms\n SET name = ?,\n status = ?,\n farm_roles_launch_order = ?,\n term_on_sync_fail = ?,\n comments = ?,\n created_by_id = ?,\n created_by_email = ?,\n changed_by_id = ?,\n changed_time = ?\n WHERE id = ?\n LIMIT 1\n ", array($this->Name, $this->Status, $this->RolesLaunchOrder, $this->TermOnSyncFail, $this->Comments, $this->ownerId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->ID)); } if (Scalr::getContainer()->analytics->enabled) { //Farm tag Scalr::getContainer()->analytics->tags->syncValue($this->ClientID, \Scalr\Stats\CostAnalytics\Entity\TagEntity::TAG_ID_FARM, $this->ID, $this->Name); //Farm owner tag Scalr::getContainer()->analytics->tags->syncValue($this->ClientID, \Scalr\Stats\CostAnalytics\Entity\TagEntity::TAG_ID_FARM_OWNER, $this->ID, $this->ownerId); } }
public static function keepSession() { $session = self::getInstance(); $tm = time() + 86400 * 30; $setHttpsCookie = $_SERVER['HTTPS'] ? true : false; $signature = self::createCookieHash($session->userId, $session->sault, $session->hash); $token = CryptoTool::hash("{$signature}:" . $session->hashpwd); setcookie('scalr_user_id', $session->userId, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_sault', $session->sault, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_hash', $session->hash, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_signature', $signature, $tm, "/", null, $setHttpsCookie, true); setcookie('scalr_token', $token, $tm, "/", null, $setHttpsCookie, false); $session->setToken($token); }
/** * Gets the list of the security groups for the specified db server. * * If server does not have required security groups this method will create them. * * @param DBServer $DBServer The DB Server instance * @param \Scalr\Service\Aws\Ec2 $ec2 Ec2 Client instance * @param string $vpcId optional The ID of VPC * @return array Returns array looks like array(groupid-1, groupid-2, ..., groupid-N) */ private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\Aws\Ec2 $ec2, $vpcId = "", \Scalr_Governance $governance = null) { $retval = array(); $checkGroups = array(); $sgGovernance = true; $allowAdditionalSgs = true; $roleBuiledSgName = \Scalr::config('scalr.aws.security_group_name') . "-rb"; if ($governance && $DBServer->farmRoleId) { $sgs = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS); if ($sgs !== null) { $governanceSecurityGroups = @explode(",", $sgs); if (!empty($governanceSecurityGroups)) { foreach ($governanceSecurityGroups as $sg) { if ($sg != '') { array_push($checkGroups, trim($sg)); } } } $sgGovernance = false; $allowAdditionalSgs = $governance->getValue(SERVER_PLATFORMS::EC2, \Scalr_Governance::AWS_SECURITY_GROUPS, 'allow_additional_sec_groups'); } } else { $sgGovernance = false; } if (!$sgGovernance || $allowAdditionalSgs) { if ($DBServer->farmRoleId != 0) { $dbFarmRole = $DBServer->GetFarmRoleObject(); if ($dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_SECURITY_GROUPS_LIST) !== null) { // New SG management $sgs = @json_decode($dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_SECURITY_GROUPS_LIST)); if (!empty($sgs)) { foreach ($sgs as $sg) { if (stripos($sg, 'sg-') === 0) { array_push($retval, $sg); } else { array_push($checkGroups, $sg); } } } } else { // Old SG management array_push($checkGroups, 'default'); array_push($checkGroups, \Scalr::config('scalr.aws.security_group_name')); if (!$vpcId) { array_push($checkGroups, "scalr-farm.{$DBServer->farmId}"); array_push($checkGroups, "scalr-role.{$DBServer->farmRoleId}"); } $additionalSgs = trim($dbFarmRole->GetSetting(\DBFarmRole::SETTING_AWS_SG_LIST)); if ($additionalSgs) { $sgs = explode(",", $additionalSgs); if (!empty($sgs)) { foreach ($sgs as $sg) { $sg = trim($sg); if (stripos($sg, 'sg-') === 0) { array_push($retval, $sg); } else { array_push($checkGroups, $sg); } } } } } } else { array_push($checkGroups, $roleBuiledSgName); } } // No name based security groups, return only SG ids. if (empty($checkGroups)) { return $retval; } // Filter groups $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups)); // If instance run in VPC, add VPC filter if ($vpcId != '') { $filter[] = array('name' => SecurityGroupFilterNameType::vpcId(), 'value' => $vpcId); } // Get filtered list of SG required by scalr; try { $list = $ec2->securityGroup->describe(null, null, $filter); $sgList = array(); foreach ($list as $sg) { /* @var $sg \Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */ if ($vpcId == '' && !$sg->vpcId || $vpcId && $sg->vpcId == $vpcId) { $sgList[$sg->groupName] = $sg->groupId; } } unset($list); } catch (Exception $e) { throw new Exception("Cannot get list of security groups (1): {$e->getMessage()}"); } foreach ($checkGroups as $groupName) { // Check default SG if ($groupName == 'default') { array_push($retval, $sgList[$groupName]); // Check Roles builder SG } elseif ($groupName == $roleBuiledSgName) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($roleBuiledSgName, "Security group for Roles Builder", $vpcId); $ipRangeList = new IpRangeList(); foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) { $ipRangeList->append(new IpRangeData($ip)); } sleep(2); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 22, 22, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList)), $securityGroupId); $sgList[$roleBuiledSgName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $roleBuiledSgName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); //Check scalr-farm.* security group } elseif (stripos($groupName, 'scalr-farm.') === 0) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmID N%s", $DBServer->farmId), $vpcId); sleep(2); $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName)); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)), $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); //Check scalr-role.* security group } elseif (stripos($groupName, 'scalr-role.') === 0) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmRoleID N%s on FarmID N%s", $DBServer->GetFarmRoleObject()->ID, $DBServer->farmId), $vpcId); sleep(2); // DB rules $dbRules = $DBServer->GetFarmRoleObject()->GetRoleObject()->getSecurityRules(); $groupRules = array(); foreach ($dbRules as $rule) { $groupRules[CryptoTool::hash($rule['rule'])] = $rule; } // Behavior rules foreach (\Scalr_Role_Behavior::getListForFarmRole($DBServer->GetFarmRoleObject()) as $bObj) { $bRules = $bObj->getSecurityRules(); foreach ($bRules as $r) { if ($r) { $groupRules[CryptoTool::hash($r)] = array('rule' => $r); } } } // Default rules $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName)); $rules = array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)); foreach ($groupRules as $rule) { $group_rule = explode(":", $rule["rule"]); $rules[] = new IpPermissionData($group_rule[0], $group_rule[1], $group_rule[2], new IpRangeData($group_rule[3])); } $ec2->securityGroup->authorizeIngress($rules, $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); } elseif ($groupName == \Scalr::config('scalr.aws.security_group_name')) { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create($groupName, "Security rules needed by Scalr", $vpcId); $ipRangeList = new IpRangeList(); foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) { $ipRangeList->append(new IpRangeData($ip)); } // TODO: Open only FOR VPC ranges $ipRangeList->append(new IpRangeData('10.0.0.0/8')); sleep(2); $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 3306, 3306, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList), new IpPermissionData('udp', 8014, 8014, $ipRangeList)), $securityGroupId); $sgList[$groupName] = $securityGroupId; } catch (Exception $e) { throw new Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage())); } } array_push($retval, $sgList[$groupName]); } else { if (!isset($sgList[$groupName])) { throw new Exception(sprintf(_("Security group '%s' is not found"), $groupName)); } else { array_push($retval, $sgList[$groupName]); } } } return $retval; }
/** * @param $qr * @param $code * @throws Exception */ public function xSettingsEnable2FaGglAction($qr, $code) { if ($this->user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL) == 1) { throw new Exception('Two-factor authentication has been already enabled for this user'); } if ($qr && $code) { if (Scalr_Util_Google2FA::verifyKey($qr, $code)) { $resetCode = CryptoTool::sault(12); $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL, 1); $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY, $this->getCrypto()->encrypt($qr)); $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE, CryptoTool::hash($resetCode)); $this->response->data(['resetCode' => $resetCode]); } else { $this->response->data(array('errors' => array('code' => 'Invalid code'))); $this->response->failure(); } } else { $this->response->failure('Invalid data'); } }
/** * @param string $scalrLogin * @param RawData $scalrPass * @param bool $scalrKeepSession * @param int $accountId * @param string $tfaGglCode * @param bool $tfaGglReset * @param string $scalrCaptcha * @param string $scalrCaptchaChallenge */ public function xLoginAction($scalrLogin, RawData $scalrPass, $scalrKeepSession = false, $accountId = 0, $tfaGglCode = '', $tfaGglReset = false, $scalrCaptcha = '', $scalrCaptchaChallenge = '') { $user = $this->loginUserGet($scalrLogin, $scalrPass, $accountId, $scalrCaptcha, $scalrCaptchaChallenge); $msg = []; // check for 2-factor auth if ($user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL) == 1) { if ($tfaGglCode) { if ($tfaGglReset) { $resetCode = $user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE); if ($resetCode != CryptoTool::hash($tfaGglCode)) { $this->response->data(["errors" => ["tfaGglCode" => "Invalid reset code"]]); $this->auditLog("user.auth.login", ['result' => 'error', 'error_message' => 'Invalid reset code']); $this->response->failure(); return; } else { $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL, ''); $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY, ''); $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE, ''); $msg = ["info" => "Two-factor authentication has been disabled."]; $this->response->success($msg["info"]); } } else { $key = $this->getCrypto()->decrypt($user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY)); if (!Scalr_Util_Google2FA::verifyKey($key, $tfaGglCode)) { $this->response->data(["errors" => ["tfaGglCode" => "Invalid code"]]); $this->auditLog("user.auth.login", ['result' => 'error', 'error_message' => 'Invalid code']); $this->response->failure(); return; } } } else { $this->response->data(["tfaGgl" => true]); $this->response->failure(); return; } } $this->loginUserCreate($user, $scalrKeepSession); try { $envId = $this->getEnvironmentId(true) ?: $user->getDefaultEnvironment()->id; } catch (Exception $e) { $envId = null; } $this->getContainer()->auditlogger->setEnvironmentId($envId)->setRuid(Scalr_Session::getInstance()->getRealUserId()); $this->auditLog("user.auth.login", $user); }
private function saveGroupRules($platform, $cloudLocation, $groupData, $newRules, $extraParams) { if ($platform != SERVER_PLATFORMS::AZURE) { $ruleTypes = array('rules', 'sgRules'); $addRulesSet = array(); $rmRulesSet = array(); foreach ($ruleTypes as $ruleType) { $addRulesSet[$ruleType] = array(); $rmRulesSet[$ruleType] = array(); foreach ($newRules[$ruleType] as $r) { if (!$r['id']) { if ($ruleType == 'rules') { $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['cidrIp']}"; } elseif ($ruleType == 'sgRules') { $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['sg']}"; } if ($platform == SERVER_PLATFORMS::EC2 && $r['type'] == self::OUTBOUND_RULE) { $rule .= ":{$r['type']}"; } $id = CryptoTool::hash($rule); if (!$groupData[$ruleType][$id]) { $addRulesSet[$ruleType][] = $r; if ($r['comment']) { if ($this->db->GetRow("SHOW TABLES LIKE 'security_group_rules_comments'")) { $this->db->Execute("\n INSERT `security_group_rules_comments`\n SET `env_id` = ?,\n `platform` = ?,\n `cloud_location` = ?,\n `vpc_id` = ?,\n `group_name` = ?,\n `rule` = ?,\n `comment` = ?\n ON DUPLICATE KEY UPDATE\n `comment` = ?\n ", array($this->getEnvironmentId(), $platform, PlatformFactory::isCloudstack($platform) ? '' : $cloudLocation, $groupData['vpcId'] ? $groupData['vpcId'] : '', $groupData['name'], $rule, $r['comment'], $r['comment'])); } else { $this->db->Execute("\n INSERT `comments`\n SET `env_id` = ?,\n `sg_name` = ?,\n `rule` = ?,\n `comment` = ?\n ON DUPLICATE KEY UPDATE\n `comment` = ?\n ", array($this->getEnvironmentId(), $groupData['name'], $rule, $r['comment'], $r['comment'])); } } } } } foreach ($groupData[$ruleType] as $r) { $found = false; foreach ($newRules[$ruleType] as $nR) { if ($nR['id'] == $r['id']) { $found = true; break; } } if (!$found) { $rmRulesSet[$ruleType][] = $r; } } } if (count($addRulesSet['rules']) > 0 || count($addRulesSet['sgRules']) > 0) { $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData, $addRulesSet, 'add')); } if (count($rmRulesSet['rules']) > 0 || count($rmRulesSet['sgRules']) > 0) { $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData, $rmRulesSet, 'remove')); } } else { $addRulesSet = []; $rmRulesSet = []; foreach ($newRules['rules'] as $r) { if (!$r['id']) { $addRulesSet['rules'][] = $r; } } foreach ($groupData['rules'] as $r) { $found = false; foreach ($newRules['rules'] as $nR) { if ($nR['id'] == $r['id']) { $found = true; break; } } if (!$found) { $rmRulesSet['rules'][] = $r; } } if (count($rmRulesSet['rules']) > 0) { $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData, $rmRulesSet, 'remove', $extraParams)); } if (count($addRulesSet['rules']) > 0) { $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData, $addRulesSet, 'add', $extraParams)); } } }
$keyId = $_SERVER['HTTP_X_SCALR_AUTH_KEY']; $token = $_SERVER['HTTP_X_SCALR_AUTH_TOKEN']; $envId = (int) $_SERVER['HTTP_X_SCALR_ENV_ID']; $pathChunks = explode('/', $path); $version = array_shift($pathChunks); $path = '/' . $path; $user = Scalr_Account_User::init(); $user->loadByApiAccessKey($keyId); if (!$user->getSetting(Scalr_Account_User::SETTING_API_ENABLED)) { throw new Exception("API disabled for this account"); } //Check IP whitelist $postData = isset($_POST['rawPostData']) ? $_POST['rawPostData'] : ''; $secretKey = $user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY); $stringToSign = "{$path}:{$keyId}:{$envId}:{$postData}:{$secretKey}"; $validToken = CryptoTool::hash($stringToSign); if ($validToken != $token) { throw new Exception("Invalid authentification token"); } // prepate input data $postDataConvert = array(); foreach (json_decode($postData, true) as $key => $value) { $postDataConvert[str_replace('.', '_', $key)] = $value; } $request = Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_API, getallheaders(), $_SERVER, $postDataConvert, $_FILES, $user->id, $envId); $request->requestApiVersion = intval(trim($version, 'v')); Scalr_Api_Controller::handleRequest($pathChunks); Scalr_UI_Response::getInstance()->sendResponse(); } catch (Exception $e) { Scalr_UI_Response::getInstance()->failure($e->getMessage()); Scalr_UI_Response::getInstance()->sendResponse();
/** * @param string $scalrLogin * @param RawData $scalrPass * @param bool $scalrKeepSession * @param int $accountId * @param string $tfaGglCode * @param bool $tfaGglReset * @param string $scalrCaptcha * @param string $scalrCaptchaChallenge */ public function xLoginAction($scalrLogin, RawData $scalrPass, $scalrKeepSession = false, $accountId = 0, $tfaGglCode = '', $tfaGglReset = false, $scalrCaptcha = '', $scalrCaptchaChallenge = '') { $user = $this->loginUserGet($scalrLogin, $scalrPass, $accountId, $scalrCaptcha, $scalrCaptchaChallenge); // check for 2-factor auth if ($user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL) == 1) { if ($tfaGglCode) { if ($tfaGglReset) { $resetCode = $user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE); if ($resetCode != CryptoTool::hash($tfaGglCode)) { $this->response->data(array('errors' => array('tfaGglCode' => 'Invalid reset code'))); $this->response->failure(); return; } else { $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL, ''); $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY, ''); $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE, ''); $this->response->success('Two-factor authentication has been disabled.'); } } else { $key = $this->getCrypto()->decrypt($user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY)); if (!Scalr_Util_Google2FA::verifyKey($key, $tfaGglCode)) { $this->response->data(array('errors' => array('tfaGglCode' => 'Invalid code'))); $this->response->failure(); return; } } } else { $this->response->data(array('tfaGgl' => true)); $this->response->failure(); return; } } $this->loginUserCreate($user, $scalrKeepSession); }