Ejemplo n.º 1
0
 /**
  * Reencrypts specified fields
  *
  * @param string     $table  Table name
  * @param string[]   $fields Fields name
  * @param string     $where  WHERE statement for SELECT query
  * @param string[]   $pks    Primary keys names
  * @param CryptoTool $source
  *
  * @return int Returns number of affected rows
  */
 public function recrypt($table, $fields, $where = '', $pks = ['id'], CryptoTool $source = null)
 {
     if ($source === null) {
         $source = $this->source;
     }
     $this->console->out("Reencrypting table '{$table}' fields:\n\t" . implode("\n\t", $fields));
     $names = '`' . implode('`, `', array_merge($pks, $fields)) . '`';
     $data = $this->db->Execute("SELECT {$names} FROM `{$table}` {$where} FOR UPDATE;");
     $params = '`' . implode('` = ?, `', $fields) . '` = ?';
     $where = '`' . implode('` = ? AND `', $pks) . '` = ?';
     $stmt = $this->db->Prepare("UPDATE `{$table}` SET {$params} WHERE {$where};");
     $affected = 0;
     foreach ($data as $entry) {
         $in = [];
         foreach ($fields as $field) {
             $in[] = $this->target->encrypt($source->_decrypt($entry[$field]));
         }
         foreach ($pks as $pk) {
             $in[] = $entry[$pk];
         }
         $this->db->Execute($stmt, $in);
         $affected += $this->db->Affected_Rows();
     }
     $this->console->out("Updated {$affected} rows!\n");
     return $affected;
 }
Ejemplo n.º 2
0
 /**
  * @test
  * @dataProvider providerTestCrypto
  */
 public function testDecryptoSzr($string)
 {
     if (self::$testSzr) {
         $key = base64_encode(self::$cryptoSzr->getCryptoKey());
         $str = escapeshellarg(self::$cryptoSzr->encrypt($string));
         exec('python ' . __DIR__ . "/CryptoToolSzr.py decrypt {$str} {$key}", $result);
         $this->assertEquals($string, $result[0]);
     } else {
         $this->markTestSkipped();
     }
 }
Ejemplo n.º 3
0
 public function save()
 {
     $this->hash = CryptoTool::sault(12);
     $this->scriptType = empty($this->scriptId) ? 'local' : 'scalr';
     if (!isset($this->orderIndex)) {
         $this->orderIndex = 10;
     }
     if (!isset($this->issync)) {
         $this->issync = 0;
     }
     parent::save();
 }
Ejemplo n.º 4
0
 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", 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);
     $tags = [['key' => \Scalr_Governance::SCALR_META_TAG_NAME, 'value' => $this->environment->applyGlobalVarsToValue(\Scalr_Governance::SCALR_META_TAG_VALUE)]];
     //Tags governance
     $governance = new \Scalr_Governance($this->environment->id);
     $gTags = (array) $governance->getValue('ec2', \Scalr_Governance::AWS_TAGS);
     if (count($gTags) > 0) {
         foreach ($gTags as $tKey => $tValue) {
             $tags[] = array('key' => $tKey, 'value' => $this->environment->applyGlobalVarsToValue($tValue));
         }
     }
     $elb->loadBalancer->addTags($elb_name, $tags);
     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)));
 }
Ejemplo n.º 5
0
 protected function ValidateRequestBySignature($signature, $timestamp, $serverid)
 {
     ksort($this->Request);
     $string_to_sign = "";
     foreach ($this->Request as $k => $v) {
         $string_to_sign .= "{$k}{$v}";
     }
     try {
         $DBServer = DBServer::LoadByID($serverid);
     } catch (Exception $e) {
         if (stristr($e->getMessage(), 'not found in database')) {
             throw new ForbiddenException($e->getMessage());
         }
         throw $e;
     }
     $valid_sign = \Scalr\Util\CryptoTool::keySign($string_to_sign, $DBServer->GetKey(true), $timestamp, static::HASH_ALGO);
     if ($valid_sign != $signature) {
         throw new ForbiddenException("Signature doesn't match");
     }
     return $DBServer;
 }
Ejemplo n.º 6
0
 public function save()
 {
     $this->hash = CryptoTool::sault(12);
     parent::save();
 }
Ejemplo n.º 7
0
 /**
  * @param   string              $newRoleName
  * @param   Scalr_Account_User  $user
  * @param   int                 $envId
  * @return  int
  * @throws Exception
  */
 public function cloneRole($newRoleName, $user, $envId)
 {
     $this->db->BeginTrans();
     $accountId = $user->getAccountId();
     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                generation      = ?,\n                os_id           = ?,\n                dtadded         = NOW(),\n                added_by_userid = ?,\n                added_by_email  = ?\n            ", array($newRoleName, $accountId ? ROLE_TYPE::CUSTOM : ROLE_TYPE::SHARED, empty($accountId) ? null : intval($accountId), empty($envId) ? null : intval($envId), $this->catId, $this->description, $this->behaviorsRaw, 2, $this->osId, $user->getId(), $user->getEmail()));
         $newRoleId = $this->db->Insert_Id();
         //Set behaviors
         foreach ($this->getBehaviors() as $behavior) {
             $this->db->Execute("INSERT IGNORE 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                ", array($newRoleId, $r7['cloud_location'], $r7['image_id'], $r7['platform']));
         }
         $props = $this->db->Execute("SELECT * FROM role_properties WHERE role_id=?", array($this->id));
         while ($p1 = $props->FetchRow()) {
             $this->db->Execute("\n                    INSERT INTO role_properties\n                    SET `role_id` = ?,\n                        `name`\t= ?,\n                        `value`\t= ?\n                    ON DUPLICATE KEY UPDATE\n                        `value` = ?\n                ", array($newRoleId, $p1['name'], $p1['value'], $p1['value']));
         }
         //Set global variables
         $variables = new Scalr_Scripting_GlobalVariables($this->clientId, $this->envId, ScopeInterface::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                    script_type = ?,\n                    script_path = ?,\n                    hash = ?\n                ", array($newRoleId, $r8['event_name'], $r8['target'], $r8['script_id'], $r8['version'], $r8['timeout'], $r8['issync'], $r8['params'], $r8['order_index'], $r8['script_type'], $r8['script_path'], CryptoTool::sault(12)));
         }
         //Set environments only for account-scope roles
         if (!empty($accountId) && empty($envId)) {
             $rsr9 = $this->db->Execute("SELECT * FROM role_environments WHERE role_id = ?", array($this->id));
             while ($r9 = $rsr9->FetchRow()) {
                 $this->db->Execute("INSERT INTO role_environments SET\n                    role_id = ?,\n                    env_id = ?\n                ", array($newRoleId, $r9['env_id']));
             }
         }
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->db->CommitTrans();
     if (!empty($newRoleId)) {
         $newRole = self::loadById($newRoleId);
         $newRole->syncAnalyticsTags();
     }
     return $newRoleId;
 }
Ejemplo n.º 8
0
 /**
  * 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;
 }
Ejemplo n.º 9
0
 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);
 }
Ejemplo n.º 10
0
 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;
 }
Ejemplo n.º 11
0
 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);
     }
 }
Ejemplo n.º 12
0
 /**
  * @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');
     }
 }
Ejemplo n.º 13
0
 /**
  * Retrieve password for a Windows machine
  *
  * @param  string $serverId
  * @throws Exception
  */
 public function xGetWindowsPasswordAction($serverId)
 {
     $this->request->restrictAccess(Acl::RESOURCE_SECURITY_RETRIEVE_WINDOWS_PASSWORDS);
     $password = $encPassword = null;
     $dbServer = DBServer::LoadByID($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 ($dbServer->platform == SERVER_PLATFORMS::AZURE) {
         $password = $dbServer->GetProperty(AZURE_SERVER_PROPERTIES::ADMIN_PASSWORD);
     } elseif ($dbServer->platform == SERVER_PLATFORMS::GCE) {
         $platform = PlatformFactory::NewPlatform(SERVER_PLATFORMS::GCE);
         /* @var $client Google_Service_Compute */
         $client = $platform->getClient($this->environment);
         $ccProps = $this->environment->keychain(SERVER_PLATFORMS::GCE)->properties;
         /* @var $info Google_Service_Compute_Instance */
         $info = $client->instances->get($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], $dbServer->cloudLocation, $dbServer->serverId);
         // More info about following code is available here:
         // https://cloud.google.com/compute/docs/instances/windows-old-auth
         //
         // Check GCE agent version
         $serialPort = $client->instances->getSerialPortOutput($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], $dbServer->cloudLocation, $dbServer->serverId);
         $serialPortContents = $serialPort->getContents();
         preg_match("/GCE Agent started( \\(version ([0-9\\.]+)\\))?\\./", $serialPortContents, $matches);
         $agentVersion = count($matches) > 1 ? (int) str_replace('.', '', $matches[2]) : 0;
         // New stuff is supported from version 3.0.0.0
         if ($agentVersion > 3000) {
             // NEW GCE AGENT
             // Get SSH key
             $config = array("digest_alg" => "sha512", "private_key_bits" => 2048, "private_key_type" => OPENSSL_KEYTYPE_RSA);
             $key = openssl_pkey_new($config);
             $details = openssl_pkey_get_details($key);
             $userObject = ['userName' => 'scalr', 'modulus' => base64_encode($details['rsa']['n']), 'exponent' => base64_encode($details['rsa']['e']), 'email' => $ccProps[Entity\CloudCredentialsProperty::GCE_SERVICE_ACCOUNT_NAME], 'expireOn' => date("c", strtotime("+10 minute"))];
             /* @var $meta Google_Service_Compute_Metadata */
             $meta = $info->getMetadata();
             $found = false;
             /* @var $item \Google_Service_Compute_MetadataItems */
             foreach ($meta as $item) {
                 if ($item->getKey() === "windows-keys") {
                     $item->setValue(json_encode($userObject, JSON_FORCE_OBJECT));
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $item = new \Google_Service_Compute_MetadataItems();
                 $item->setKey("windows-keys");
                 $item->setValue(json_encode($userObject, JSON_FORCE_OBJECT));
                 $meta[count($meta)] = $item;
             }
             $client->instances->setMetadata($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], $dbServer->cloudLocation, $dbServer->serverId, $meta);
             //Monitor serial port #4
             for ($i = 0; $i < 10; $i++) {
                 $serialPortInfo = $client->instances->getSerialPortOutput($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], $dbServer->cloudLocation, $dbServer->serverId, ['port' => 4]);
                 $lines = explode("\n", $serialPortInfo->getContents());
                 foreach ($lines as $line) {
                     $obj = json_decode(trim($line));
                     if (isset($obj->modulus) && $obj->modulus == $userObject['modulus']) {
                         $encPassword = base64_decode($obj->encryptedPassword);
                         break;
                     }
                 }
                 if ($encPassword) {
                     break;
                 }
                 sleep(2);
             }
             if ($encPassword) {
                 openssl_private_decrypt($encPassword, $password, $key, OPENSSL_PKCS1_OAEP_PADDING);
                 $encPassword = null;
             } else {
                 throw new Exception("Windows password is not available yet. Please try again in couple minutes.");
             }
         } else {
             // OLD GCE AGENT
             foreach ($info->getMetadata() as $meta) {
                 /* @var $meta Google_Service_Compute_MetadataItems */
                 if ($meta->getKey() == 'gce-initial-windows-password') {
                     $password = $meta->getValue();
                     break;
                 }
             }
         }
     } 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 is supported by '{$dbServer->platform}' cloud");
     }
     if ($encPassword) {
         try {
             $sshKey = (new SshKey())->loadGlobalByFarmId($dbServer->envId, $dbServer->platform, $dbServer->GetCloudLocation(), $dbServer->farmId);
             $password = CryptoTool::opensslDecrypt(base64_decode($encPassword), $sshKey->privateKey);
         } catch (Exception $e) {
             //Do nothing. Error already handled in UI (If no password returned)
         }
     }
     $this->response->data(array('password' => $password, 'encodedPassword' => $encPassword));
 }
Ejemplo n.º 14
0
 /**
  * @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);
 }
Ejemplo n.º 15
0
 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));
         }
     }
 }
Ejemplo n.º 16
0
    $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();
Ejemplo n.º 17
0
 public static function getKey()
 {
     return CryptoTool::sault(8);
 }
Ejemplo n.º 18
0
 /**
  * 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);
 }
Ejemplo n.º 19
0
 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 ($dbServer->platform == SERVER_PLATFORMS::GCE) {
         $platform = PlatformFactory::NewPlatform(SERVER_PLATFORMS::GCE);
         $client = $platform->getClient($this->environment, $this->getParam('cloudLocation'));
         /* @var $client Google_Service_Compute */
         $info = $client->instances->get($this->environment->getPlatformConfigValue(GoogleCEPlatformModule::PROJECT_ID), $dbServer->cloudLocation, $dbServer->serverId);
         /* @var $info Google_Service_Compute_Instance */
         foreach ($info->getMetadata() as $meta) {
             /* @var $meta Google_Service_Compute_MetadataItems */
             if ($meta->getKey() == 'gce-initial-windows-password') {
                 $password = $meta->getValue();
                 break;
             }
         }
     } 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) {
         try {
             $privateKey = Scalr_SshKey::init()->loadGlobalByFarmId($dbServer->envId, $dbServer->farmId, $dbServer->GetCloudLocation(), $dbServer->platform);
             $password = CryptoTool::opensslDecrypt(base64_decode($encPassword), $privateKey->getPrivate());
         } catch (Exception $e) {
             //Do nothing. Error already handled in UI (If no password returned)
         }
     }
     $this->response->data(array('password' => $password, 'encodedPassword' => $encPassword));
 }
Ejemplo n.º 20
0
Archivo: Role.php Proyecto: scalr/scalr
 /**
  * Set scripts of the Role
  * TODO refactor this method to new Entities
  *
  * @param   array   $scripts
  */
 public function setScripts($scripts)
 {
     if (!$this->id) {
         return;
     }
     if (!is_array($scripts)) {
         return;
     }
     $ids = array();
     foreach ($scripts as $script) {
         // TODO: check permission for script_id
         if (!$script['role_script_id']) {
             $this->db()->Execute('INSERT INTO role_scripts SET
                 `role_id` = ?,
                 `event_name` = ?,
                 `target` = ?,
                 `script_id` = ?,
                 `version` = ?,
                 `timeout` = ?,
                 `issync` = ?,
                 `params` = ?,
                 `order_index` = ?,
                 `hash` = ?,
                 `script_path` = ?,
                 `run_as` = ?,
                 `script_type` = ?
             ', array($this->id, $script['event_name'], $script['target'], $script['script_id'] != 0 ? $script['script_id'] : NULL, $script['version'], $script['timeout'], $script['isSync'], serialize($script['params']), $script['order_index'], !$script['hash'] ? CryptoTool::sault(12) : $script['hash'], $script['script_path'], $script['run_as'], $script['script_type']));
             $ids[] = $this->db()->Insert_ID();
         } else {
             $this->db()->Execute('UPDATE role_scripts SET
                 `event_name` = ?,
                 `target` = ?,
                 `script_id` = ?,
                 `version` = ?,
                 `timeout` = ?,
                 `issync` = ?,
                 `params` = ?,
                 `order_index` = ?,
                 `script_path` = ?,
                 `run_as` = ?,
                 `script_type` = ?
                 WHERE id = ? AND role_id = ?
             ', array($script['event_name'], $script['target'], $script['script_id'] != 0 ? $script['script_id'] : NULL, $script['version'], $script['timeout'], $script['isSync'], serialize($script['params']), $script['order_index'], $script['script_path'], $script['run_as'], $script['script_type'], $script['role_script_id'], $this->id));
             $ids[] = $script['role_script_id'];
         }
     }
     $toRemove = $this->db()->Execute('SELECT id, hash FROM role_scripts WHERE role_id = ? AND id NOT IN (\'' . implode("','", $ids) . '\')', array($this->id));
     while ($rScript = $toRemove->FetchRow()) {
         $this->db()->Execute("DELETE FROM farm_role_scripting_params WHERE hash = ? AND farm_role_id IN (SELECT id FROM farm_roles WHERE role_id = ?)", array($rScript['hash'], $this->id));
         $this->db()->Execute("DELETE FROM role_scripts WHERE id = ?", array($rScript['id']));
     }
 }
Ejemplo n.º 21
0
Archivo: Elb.php Proyecto: mheydt/scalr
 /**
  * @param string     $cloudLocation                     Ec2 Region
  * @param JsonData   $listeners                         Listeners list
  * @param bool       $crossLoadBalancing                Enable Cross balancing
  * @param JsonData   $healthcheck                       Health check data
  * @param string     $scheme                            optional Scheme
  * @param JsonData   $securityGroups                    optional Security groups
  * @param string     $vpcId                             optional Vpc id
  * @param JsonData   $zones                             optional Availability zones
  * @param JsonData   $subnets                           optional Subnets
  * @param string     $name                              optional Name
  * @throws Exception
  */
 public function xCreateAction($cloudLocation, JsonData $listeners, $crossLoadBalancing, JsonData $healthcheck, $scheme = null, JsonData $securityGroups = null, $vpcId = null, JsonData $zones = null, JsonData $subnets = null, $name = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE);
     $elb = $this->environment->aws($cloudLocation)->elb;
     //prepare listeners
     $listenersList = new ListenerList();
     foreach ($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])));
     }
     $zones = !empty($zones) ? (array) $zones : null;
     $subnets = !empty($subnets) ? (array) $subnets : null;
     if (empty($name)) {
         $name = sprintf("scalr-%s-%s", CryptoTool::sault(10), rand(100, 999));
     } else {
         if (!preg_match('/^[-a-zA-Z0-9]+$/', $name)) {
             throw new Exception('Load Balancer names must only contain alphanumeric characters or dashes.');
         }
     }
     $healthCheckType = new HealthCheckData();
     $healthCheckType->target = $healthcheck['target'];
     $healthCheckType->healthyThreshold = $healthcheck['healthyThreshold'];
     $healthCheckType->interval = $healthcheck['interval'];
     $healthCheckType->timeout = $healthcheck['timeout'];
     $healthCheckType->unhealthyThreshold = $healthcheck['unhealthyThreshold'];
     $securityGroupIds = [];
     foreach ($securityGroups as $securityGroup) {
         $securityGroupIds[] = $securityGroup['id'];
     }
     $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkSecurityGroupsPolicy($securityGroups, Aws::SERVICE_INTERFACE_ELB);
     if ($result === true) {
         $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkVpcPolicy($vpcId, $subnets, $cloudLocation);
     }
     if ($result !== true) {
         throw new Exception($result);
     }
     //Creates a new ELB
     $dnsName = $elb->loadBalancer->create($name, $listenersList, $zones, $subnets, !empty($securityGroupIds) ? $securityGroupIds : null, !empty($scheme) ? $scheme : null);
     if ($crossLoadBalancing) {
         $attributes = new AttributesData();
         $attributes->setCrossZoneLoadBalancing(new CrossZoneLoadBalancingData($crossLoadBalancing));
         $requestData = new ModifyLoadBalancerAttributes($name, $attributes);
         $elb->loadBalancer->modifyAttributes($requestData);
     }
     $elb->loadBalancer->addTags($name, $this->getEnvironment()->getAwsTags());
     try {
         $elb->loadBalancer->configureHealthCheck($name, $healthCheckType);
     } catch (Exception $e) {
         $elb->loadBalancer->delete($name);
         throw $e;
     }
     $lb = $elb->loadBalancer->describe($name)->get(0);
     // return all as in xListElb
     $this->response->data(['elb' => ['name' => $name, 'dnsName' => $dnsName, 'dtcreated' => $lb->createdTime->format('c'), 'subnets' => $lb->subnets]]);
 }
Ejemplo n.º 22
0
 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 = 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();
     }
 }
Ejemplo n.º 23
0
 /**
  * @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);
 }