public static function getIdByUrlAndAuth($url, $authInfo) { $crypto = new Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8); $cryptoKey = @file_get_contents(dirname(__FILE__) . "/../../etc/.cryptokey"); $eAuthInfo = $crypto->encrypt(serialize($authInfo), $cryptoKey); return Core::GetDBInstance()->GetOne("SELECT id FROM dm_sources WHERE `url`=? AND auth_info=?", array($url, $eAuthInfo)); }
/** * @return Scalr_Util_CryptoTool */ protected function getCrypto() { if (!$this->crypto) { $this->crypto = new Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8); $this->crypto->setCryptoKey(@file_get_contents(dirname(__FILE__) . "/../../../etc/.cryptokey")); } return $this->crypto; }
protected function run1($stage) { $crypto = new \Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8); $cryptoKey = @file_get_contents(SRCPATH . "/../etc/.cryptokey"); $this->console->out('Creating field ssl_simple_pkey'); $this->db->Execute('ALTER TABLE services_ssl_certs ADD `ssl_simple_pkey` text'); $this->console->out('Encrypting values'); $values = $this->db->GetAll('SELECT * FROM services_ssl_certs'); foreach ($values as $value) { if ($value['ssl_pkey']) { $this->db->Execute('UPDATE services_ssl_certs SET ssl_simple_pkey = ?, ssl_pkey = ? WHERE id = ?', array($value['ssl_pkey'], $crypto->encrypt($value['ssl_pkey'], $cryptoKey), $value['id'])); } } }
public function xCreateAction() { $this->request->defineParams(array('listeners' => array('type' => 'json'), 'healthcheck' => array('type' => 'json'), 'zones' => array('type' => 'array'), 'subnets' => array('type' => 'array'), 'scheme' => array('type' => 'string'))); $healthCheck = $this->getParam('healthcheck'); $elb = $this->environment->aws($this->getParam('cloudLocation'))->elb; //prepare listeners $listenersList = new ListenerList(); $li = 0; foreach ($this->getParam('listeners') as $listener) { $listener_chunks = explode("#", $listener); $listenersList->append(new ListenerData(trim($listener_chunks[1]), trim($listener_chunks[2]), trim($listener_chunks[0]), null, trim($listener_chunks[3]))); } $availZones = $this->getParam('zones'); $subnets = $this->getParam('subnets'); $scheme = $this->getParam('scheme'); $elb_name = sprintf("scalr-%s-%s", Scalr_Util_CryptoTool::sault(10), rand(100, 999)); $healthCheckType = new HealthCheckData(); $healthCheckType->target = $healthCheck['target']; $healthCheckType->healthyThreshold = $healthCheck['healthyThreshold']; $healthCheckType->interval = $healthCheck['interval']; $healthCheckType->timeout = $healthCheck['timeout']; $healthCheckType->unhealthyThreshold = $healthCheck['unhealthyThreshold']; //Creates a new ELB $dnsName = $elb->loadBalancer->create($elb_name, $listenersList, !empty($availZones) ? $availZones : null, !empty($subnets) ? $subnets : null, null, !empty($scheme) ? $scheme : null); try { $elb->loadBalancer->configureHealthCheck($elb_name, $healthCheckType); } catch (Exception $e) { $elb->loadBalancer->delete($elb_name); throw $e; } // return all as in xListElb $this->response->data(array('elb' => array('name' => $elb_name, 'dnsName' => $dnsName))); }
protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1') { try { $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_POST); $postData = json_encode($args); $stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY; $validToken = Scalr_Util_CryptoTool::hash($stringToSign); $httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId)); $httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}"); $httpRequest->setPostFields(array('rawPostData' => $postData)); foreach ($files as $name => $file) { $httpRequest->addPostFile($name, $file); } $httpRequest->send(); if ($this->debug) { print "<pre>"; var_dump($httpRequest->getRequestMessage()); var_dump($httpRequest->getResponseCode()); var_dump($httpRequest->getResponseData()); } $data = $httpRequest->getResponseData(); return @json_decode($data['body']); } catch (Exception $e) { echo "<pre>"; if ($this->debug) { var_dump($e); } else { var_dump($e->getMessage()); } } }
public function supportAction() { if ($this->user) { $args = array("name" => $this->user->fullname, "AccountID" => $this->user->getAccountId(), "email" => $this->user->getEmail(), "expires" => date("D M d H:i:s O Y", time() + 120)); $token = Scalr_Util_CryptoTool::generateTenderMultipassToken(json_encode($args)); $this->response->setRedirect("http://support.scalr.net/?sso={$token}"); } else { $this->response->setRedirect("/"); } }
public function xGetWindowsPasswordAction() { $this->request->restrictAccess(Acl::RESOURCE_SECURITY_RETRIEVE_WINDOWS_PASSWORDS); $this->request->defineParams(array('serverId')); $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); if ($dbServer->platform == SERVER_PLATFORMS::EC2) { $env = Scalr_Environment::init()->loadById($dbServer->envId); $ec2 = $env->aws($dbServer->GetCloudLocation())->ec2; $encPassword = $ec2->instance->getPasswordData($dbServer->GetCloudServerID()); $privateKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->farmId, $dbServer->GetCloudLocation(), $dbServer->platform); $password = Scalr_Util_CryptoTool::opensslDecrypt(base64_decode($encPassword->passwordData), $privateKey->getPrivate()); } elseif (PlatformFactory::isOpenstack($dbServer->platform)) { $env = Scalr_Environment::init()->loadById($dbServer->envId); $os = $env->openstack($dbServer->platform, $dbServer->GetCloudLocation()); //TODO: } else { throw new Exception("Requested operation supported only by EC2"); } $this->response->data(array('password' => $password)); }
private function getSshKeygenValue($args, $tmpFileContents, $readTmpFile = false) { $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $filePath = CACHEPATH . "/_tmp." . Scalr_Util_CryptoTool::hash($tmpFileContents); if (!$readTmpFile) { @file_put_contents($filePath, $tmpFileContents); @chmod($filePath, 0600); } $pipes = array(); $process = @proc_open("/usr/bin/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; }
protected static function createCookieHash($userId, $sault, $hash) { $pass = self::getUserPassword($userId); return Scalr_Util_CryptoTool::hash("{$sault}:{$hash}:{$userId}:{$pass}:" . self::getInstance()->hashpwd); }
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 = Scalr_Util_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); }
private function saveRules($groupData, $newRules) { $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']}"; } $id = Scalr_Util_CryptoTool::hash($rule); if (!$groupData[$ruleType][$id]) { $addRulesSet[$ruleType][] = $r; if ($r['comment']) { //UNIQUE KEY `main` (`env_id`,`sg_name`,`rule`) $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->updateRules($groupData['platform'], $groupData['cloudLocation'], $groupData['id'], $addRulesSet, 'add'); } if (count($rmRulesSet['rules']) > 0 || count($rmRulesSet['sgRules']) > 0) { $this->updateRules($groupData['platform'], $groupData['cloudLocation'], $groupData['id'], $rmRulesSet, 'remove'); } }
private function saveGroupRules($platform, $cloudLocation, $groupData, $newRules) { $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']}"; } $id = Scalr_Util_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['id'], $addRulesSet, 'add')); } if (count($rmRulesSet['rules']) > 0 || count($rmRulesSet['sgRules']) > 0) { $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData['id'], $rmRulesSet, 'remove')); } }
/** * 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; $vpcId = null; if ($governance) { $sgs = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_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::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS, 'allow_additional_sec_groups'); } } if (!$sgGovernance || $allowAdditionalSgs) { if ($DBServer->farmRoleId != 0) { $dbFarmRole = $DBServer->GetFarmRoleObject(); if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST) !== null) { // New SG management $sgs = @json_decode($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_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 { array_push($checkGroups, 'scalr-rb-system'); } } // No name based security groups, return only SG ids. if (empty($checkGroups)) { return $retval; } // Filter groups $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups)); // 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 == 'scalr-rb-system') { if (!isset($sgList[$groupName])) { try { $securityGroupId = $ec2->securityGroup->create('scalr-rb-system', "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['scalr-rb-system'] = $securityGroupId; } catch (\Exception $e) { throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), 'scalr-rb-system', $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[\Scalr_Util_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[\Scalr_Util_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 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->getAccountId() && $user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_2FA) || !$user->getAccountId()) && $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 != Scalr_Util_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); }
/** * @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 = Scalr_Util_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, Scalr_Util_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'); } }
public function cloneRole($newRoleName, $accountId, $envId) { $this->db->BeginTrans(); try { $this->db->Execute("INSERT INTO roles SET\n name = ?,\n origin = ?,\n client_id = ?,\n env_id = ?,\n cat_id = ?,\n description = ?,\n behaviors = ?,\n history = ?,\n generation = ?,\n os = ?,\n os_family = ?,\n os_version = ?,\n os_generation = ?\n ", array($newRoleName, ROLE_TYPE::CUSTOM, $accountId, $envId, $this->catId, $this->description, $this->behaviorsRaw, "*cloned from {$this->name} ({$this->id})*", 2, $this->os, $this->osFamily, $this->osVersion, $this->osGeneration)); $newRoleId = $this->db->Insert_Id(); //Set behaviors foreach ($this->getBehaviors() as $behavior) { $this->db->Execute("INSERT INTO role_behaviors SET role_id = ?, behavior = ?", array($newRoleId, $behavior)); } // Set images $rsr7 = $this->db->Execute("SELECT * FROM role_images WHERE role_id = ?", array($this->id)); while ($r7 = $rsr7->FetchRow()) { $this->db->Execute("INSERT INTO role_images SET\n `role_id` = ?,\n `cloud_location` = ?,\n `image_id` = ?,\n `platform` = ?,\n `architecture` = ?,\n `agent_version` = ?\n ", array($newRoleId, $r7['cloud_location'], $r7['image_id'], $r7['platform'], $r7['architecture'], $r7['agent_version'])); } //Set tags $rsr1 = $this->db->Execute("SELECT * FROM role_tags WHERE role_id = ?", array($this->id)); $tags = array(); while ($r1 = $rsr1->FetchRow()) { $this->db->Execute("INSERT INTO role_tags SET\n `role_id` = ?,\n `tag` = ?\n ", array($newRoleId, $r1['tag'])); } //Set software $rsr2 = $this->db->Execute("SELECT * FROM role_software WHERE role_id = ?", array($this->id)); while ($r2 = $rsr2->FetchRow()) { $this->db->Execute("INSERT INTO role_software SET\n `role_id` = ?,\n `software_name` = ?,\n `software_version` = ?,\n `software_key` = ?\n ", array($newRoleId, $r2['software_name'], $r2['software_version'], $r2['software_key'])); } //Set global variables $variables = new Scalr_Scripting_GlobalVariables($this->envId, Scalr_Scripting_GlobalVariables::SCOPE_ROLE); $variables->setValues($variables->getValues($this->id), $newRoleId); //Set scripts $rsr8 = $this->db->Execute("SELECT * FROM role_scripts WHERE role_id = ?", array($this->id)); while ($r8 = $rsr8->FetchRow()) { $this->db->Execute("INSERT INTO role_scripts SET\n role_id = ?,\n event_name = ?,\n target = ?,\n script_id = ?,\n version = ?,\n timeout = ?,\n issync = ?,\n params = ?,\n order_index = ?,\n hash = ?\n ", array($newRoleId, $r8['event_name'], $r8['target'], $r8['script_id'], $r8['version'], $r8['timeout'], $r8['issync'], $r8['params'], $r8['order_index'], Scalr_Util_CryptoTool::sault(12))); } } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } $this->db->CommitTrans(); return $newRoleId; }
public function xGetWindowsPasswordAction() { $this->request->restrictAccess(Acl::RESOURCE_SECURITY_RETRIEVE_WINDOWS_PASSWORDS); $this->request->defineParams(array('serverId')); $dbServer = DBServer::LoadByID($this->getParam('serverId')); $this->user->getPermissions()->validate($dbServer); if ($dbServer->platform == SERVER_PLATFORMS::EC2) { $env = Scalr_Environment::init()->loadById($dbServer->envId); $ec2 = $env->aws($dbServer->GetCloudLocation())->ec2; $encPassword = $ec2->instance->getPasswordData($dbServer->GetCloudServerID()); $encPassword = str_replace('\\/', '/', trim($encPassword->passwordData)); } elseif (PlatformFactory::isOpenstack($dbServer->platform)) { if (in_array($dbServer->platform, array(SERVER_PLATFORMS::RACKSPACENG_UK, SERVER_PLATFORMS::RACKSPACENG_US))) { $password = $dbServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS); } else { $env = Scalr_Environment::init()->loadById($dbServer->envId); $os = $env->openstack($dbServer->platform, $dbServer->GetCloudLocation()); //TODO: Check is extension supported $encPassword = trim($os->servers->getEncryptedAdminPassword($dbServer->GetCloudServerID())); } } else { throw new Exception("Requested operation supported only by EC2"); } if ($encPassword) { $privateKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->envId, $dbServer->farmId, $dbServer->GetCloudLocation(), $dbServer->platform); $password = Scalr_Util_CryptoTool::opensslDecrypt(base64_decode($encPassword), $privateKey->getPrivate()); } $this->response->data(array('password' => $password, 'encodedPassword' => $encPassword)); }
public function save() { if (!$this->ID) { $this->ID = 0; $this->Hash = substr(Scalr_Util_CryptoTool::hash(uniqid(rand(), true)), 0, 14); //FIXME This is F*CKINK BULLSHIT! REMOVE Scalr_UI_Request From here. if (!$this->ClientID) { $this->ClientID = Scalr_UI_Request::getInstance()->getUser()->getAccountId(); } if (!$this->EnvID) { $this->EnvID = Scalr_UI_Request::getInstance()->getEnvironment()->id; } } if ($this->DB->GetOne('SELECT id FROM farms WHERE name = ? AND env_id = ? AND id != ? LIMIT 1', array($this->Name, $this->EnvID, $this->ID))) { throw new Exception('This name already used'); } if (!$this->ID) { $this->DB->Execute("INSERT INTO farms SET\n status\t\t= ?,\n name\t\t= ?,\n clientid\t= ?,\n env_id\t\t= ?,\n hash\t\t= ?,\n created_by_id = ?,\n created_by_email = ?,\n changed_by_id = ?,\n changed_time = ?,\n dtadded\t\t= NOW(),\n farm_roles_launch_order = ?,\n comments = ?\n ", array(FARM_STATUS::TERMINATED, $this->Name, $this->ClientID, $this->EnvID, $this->Hash, $this->createdByUserId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->RolesLaunchOrder, $this->Comments)); $this->ID = $this->DB->Insert_ID(); } else { $this->DB->Execute("UPDATE farms SET\n name\t\t= ?,\n status\t\t= ?,\n farm_roles_launch_order = ?,\n term_on_sync_fail = ?,\n comments = ?,\n changed_by_id = ?,\n changed_time = ?\n WHERE id = ?\n ", array($this->Name, $this->Status, $this->RolesLaunchOrder, $this->TermOnSyncFail, $this->Comments, $this->changedByUserId, $this->changedTime, $this->ID)); } }
public function save() { $container = \Scalr::getContainer(); if (!$this->ID) { $this->ID = 0; $this->Hash = substr(Scalr_Util_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->createdByUserId, $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->createdByUserId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->ID)); } if (Scalr::getContainer()->analytics->enabled) { Scalr::getContainer()->analytics->tags->syncValue($this->ClientID, \Scalr\Stats\CostAnalytics\Entity\TagEntity::TAG_ID_FARM, $this->ID, $this->Name); } }
$envId = (int) $_SERVER['HTTP_X_SCALR_ENV_ID']; $pathChunks = explode('/', $path); $version = array_shift($pathChunks); $path = '/' . $path; //if (! $envId) //throw new Exception('Environment not defined'); // TODO: how to check if needed ? $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 = Scalr_Util_CryptoTool::hash($stringToSign); if ($validToken != $token) { throw new Exception("Invalid authentification token"); } Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_API, $user->id, $envId); // prepate input data $postDataConvert = array(); foreach (json_decode($postData, true) as $key => $value) { $postDataConvert[str_replace('.', '_', $key)] = $value; } Scalr_Api_Controller::handleRequest($pathChunks, $postDataConvert); } catch (Exception $e) { Scalr_UI_Response::getInstance()->failure($e->getMessage()); Scalr_UI_Response::getInstance()->sendResponse(); }
<?php require_once __DIR__ . "/../src/prepend.inc.php"; use Scalr\Service\OpenStack\OpenStack; use Scalr\Service\OpenStack\OpenStackConfig; use Scalr\Service\OpenStack\Services\Network\Type\CreateSubnet; use Scalr\Service\OpenStack\Services\Network\Type\CreateRouter; use Scalr\Modules\Platforms\Openstack\OpenstackPlatformModule; use Scalr\Service\OpenStack\Services\Servers\Type\ServersExtension; $validator = new Scalr_Validator(); $crypto = new Scalr_Util_CryptoTool(MCRYPT_TRIPLEDES, MCRYPT_MODE_CFB, 24, 8); if (!$_REQUEST['update'] && !$_REQUEST['delete']) { if (!$_REQUEST['name']) { $err['name'] = _("Account name required"); } $name = $_REQUEST['name']; $password = $crypto->sault(10); } if ($validator->validateEmail($_REQUEST['email'], null, true) !== true) { $err['email'] = _("Invalid E-mail address"); } $email = $_REQUEST['email']; function getOpenStackOption($name) { return SERVER_PLATFORMS::ECS . "." . constant('Scalr\\Modules\\Platforms\\Openstack\\OpenstackPlatformModule::' . $name); } if (count($err) == 0) { if ($_REQUEST['delete']) { $user = Scalr_Account_User::init()->loadByEmail($email); if (!$user) { throw new Exception("User Not Found");
public function xSaveAction() { $user = Scalr_Account_User::init(); $validator = new Scalr_Validator(); if (!$this->getParam('email')) { throw new Scalr_Exception_Core('Email must be provided.'); } if ($validator->validateEmail($this->getParam('email'), null, true) !== true) { throw new Scalr_Exception_Core('Email should be correct'); } if ($this->user->canManageAcl() || $this->user->isTeamOwner()) { $newUser = false; if ($this->getParam('id')) { $user->loadById((int) $this->getParam('id')); if (!$this->user->canEditUser($user)) { throw new Scalr_Exception_InsufficientPermissions(); } $user->updateEmail($this->getParam('email')); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_USERS, 1); $user->create($this->getParam('email'), $this->user->getAccountId()); $user->type = Scalr_Account_User::TYPE_TEAM_USER; $newUser = true; } $sendResetLink = false; if (!$this->getParam('password')) { $password = Scalr_Util_CryptoTool::sault(10); $sendResetLink = true; } else { $password = $this->getParam('password'); } if ($password != '******') { $user->updatePassword($password); } if (in_array($this->getParam('status'), array(Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE)) && !$user->isAccountOwner()) { $user->status = $this->getParam('status'); } $user->fullname = $this->getParam('fullname'); $user->comments = $this->getParam('comments'); $user->save(); if ($this->getParam('enableApi')) { $keys = Scalr::GenerateAPIKeys(); $user->setSetting(Scalr_Account_User::SETTING_API_ENABLED, true); $user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']); $user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']); } if ($newUser) { if ($sendResetLink) { try { $hash = $this->getCrypto()->sault(10); $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash); $clientinfo = array('email' => $user->getEmail(), 'fullname' => $user->fullname); // Send reset password E-mail $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_account_confirm.eml', array("{{fullname}}" => $clientinfo['fullname'], "{{pwd_link}}" => "https://{$_SERVER['HTTP_HOST']}/#/guest/updatePassword/?hash={$hash}"), $clientinfo['email'], $clientinfo['fullname']); } catch (Exception $e) { } } } $this->response->data(array('user' => array('id' => $user->getId(), 'email' => $user->getEmail(), 'fullname' => $user->fullname))); $this->response->success('User successfully saved'); } else { throw new Scalr_Exception_InsufficientPermissions(); } }