private function _genLicense($expires) { $l = new OSS_License_MD5(); for ($i = 0; $i < 10; $i++) { $l->setParam("P{$i}", OSS_String::random(20)); } $l->setParam("Expires", $expires); return new OSS_License_MD5(parse_ini_string($l->generate())); }
/** * Test that decryption with a bad password returns false */ public function testsFailedEncryptDecrypt() { $plain = OSS_String::random(64); $password = OSS_String::random(12); while (($password2 = OSS_String::random(12)) == $password) { } $encrypted = OSS_Crypt_GibberishAES::encrypt($plain, $password); $decrypted = OSS_Crypt_GibberishAES::decrypt($encrypted, $password2); $this->assertFalse($decrypted); }
/** * Fix the formatting of an address line. * * @param string $value The value to filter * @return string */ public function filter($value) { if ($value == '') { return $value; } foreach (preg_split("/[ \\-\\']/", mb_strtolower($value)) as $vOneValue) { $value = OSS_String::mb_str_replace($vOneValue, OSS_String::mb_ucfirst($vOneValue), $value); } return $value; }
/** * Fix the formatting of a person's lastname. * * @param string $value The value to filter * @return string */ public function filter($value) { if ($value == '') { return $value; } foreach (preg_split("/[ \\-]/", mb_strtolower($value)) as $vOneName) { $value = OSS_String::mb_str_replace($vOneName, OSS_String::mb_ucfirst($vOneName), $value); } if (mb_strpos(mb_strtoupper($value), "O'") !== false) { preg_match("/O\\'./", $value, $vMatches); $value = OSS_String::mb_str_replace($vMatches[0], mb_strtoupper($vMatches[0]), $value); } return $value; }
/** * Creates PDF and returns path. * * First it renders and creates HTML file and then it creates pdf file. * It removes new HTML file and returns path to new pdf file. * * PDF file removing is added in all other methods where _processPDF are called. * * @return string */ private function _processPDF() { $ts = date('YmdHis'); $tn = APPLICATION_PATH . "/../var/tmp/OSS_PDF_" . $ts . '_' . OSS_String::random(8, true, true, true, '', ''); $fhtml = "{$tn}.html"; $fpdf = "{$tn}.pdf"; if (@file_put_contents($fhtml, $this->_html->render()) === false) { return false; } $path = Zend_Registry::get('options')['includePaths']['osslibrary'] . "/bin"; @exec(escapeshellcmd($path . "/wkhtmltopdf-amd64 -q '{$fhtml}' '{$fpdf}'")); @unlink($fhtml); if (!file_exists($fpdf) || !filesize($fpdf)) { return false; } return $fpdf; }
public function addAction() { if (count($this->getUser()->getApiKeys()) >= 10) { $this->addMessage('We currently have a limit of 10 API keys per user. Please contact us if you require more.', OSS_Message::ERROR); $this->redirect('api-key/list'); } $key = new \Entities\ApiKey(); $key->setUser($this->getUser()); $key->setCreated(new DateTime()); $key->setApiKey(OSS_String::random(48, true, true, true, '', '')); $key->setAllowedIPs(''); $key->setExpires(null); $key->setLastseenFrom(''); $this->getD2EM()->persist($key); $this->getUser()->addApiKey($key); $this->getD2EM()->flush(); $this->addMessage('Your new API key has been created - <code>' . $key->getApiKey() . '</code>', OSS_Message::SUCCESS); $this->redirect('api-key/list'); }
/** * Instantiates a new DBAL connection (or returns an existing one. * * @param array|Zend_Config $params The Doctrine2 DBAL params (@see http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html) * @param string $name The name of the connection (used especially when managing multiple connections). Default: ''default'' * @returns \Doctrine\DBAL\Connection * @throws OSS_Doctrine2_Exception */ protected function getDBAL($params = null, $name = null) { // resolve name if ($name === null) { if ($this->_dbalAltDefaultName === null) { $this->_dbalAltDefaultName = '__OSS_FW_' . OSS_String::random(32, true, true, true, '', ''); } $name = $this->_dbalAltDefaultName; } if (!isset($this->_dbalConnections[$name])) { if ($params === null) { throw new OSS_Doctrine2_Exception("No parameters for new DBAL connection"); } if ($params instanceof Zend_Config) { $params = $params->toArray(); } $config = new \Doctrine\DBAL\Configuration(); $this->_dbalConnections[$name] = \Doctrine\DBAL\DriverManager::getConnection($params, $config); } return $this->_dbalConnections[$name]; }
/** * Attaches or embeds a file to/into an email. Embedding the images into an HTML letter happens automatically. * * @param string $filePath the path to the file to attach * @param boolean $embed default false if true then the file will be embedded instead of attached * @return boolean */ public function attachFile($filePath, $embed = false) { if ($filePath == '' || $filePath == array()) { return true; } //[FIXME] I thing here should be false if (!@is_readable($filePath)) { $filePath = OSS_String::mb_str_replace(Zend_Controller_Front::getInstance()->getBaseUrl() . '/', '', $filePath); } if (@is_readable($filePath)) { $pathInfo = pathinfo($filePath); $attachment = $this->createAttachment(@file_get_contents($filePath)); $attachment->type = $this->getMimeByExtension($pathInfo['extension']); $attachment->encoding = Zend_Mime::ENCODING_BASE64; if ($embed == false) { $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $attachment->filename = basename($filePath); } else { $attachment->disposition = Zend_Mime::DISPOSITION_INLINE; $attachment->id = 'cid_' . md5_file($filePath); $this->setBodyHtml(OSS_String::mb_str_replace($filePath, "cid:{$attachment->id}", $this->getBodyHtml(true))); } return true; } return false; }
/** * Generates a random MAC address. * * @param bool $upperCase default false * @return string */ public static function randomMacAddress($upperCase = false) { $retArr = array(); for ($x = 1; $x <= 6; $x++) { $retArr[] = OSS_String::random(2, false, false, false, '0123456789abcdef', ''); } $retVal = implode(':', $retArr); return $upperCase ? strtoupper($retVal) : $retVal; }
/** * Hash password for davical user. * * It hashes three davical supported types hash: * * First and most unsecured hash is plain it just add two start infont of password. * * Second is md5 result is *<salt>* (where <salt> is a random series of characters not including '*') * then the rest of the string is a hash of (password + salt), i.e. a salted hash. * * Third is SSHA result is is "*<salt>*<LDAP compatible SSHA password>" and the <LDAP compatible SSHA password> * is "{SSHA}<SHA-1 salted hash>". Read the code in /usr/share/awl/inc/AWLUtilities.php if you want to * understand that format more deeply! * * @param string $password Users password to login. * @param string $method Hash method * @return string return hashed string. */ public static function hashPassword($password, $method) { $salt = OSS_String::salt(9); if ($method == self::PASSWORD_HASH_PLAIN) { return "**" . $password; } else { if ($method == self::PASSWORD_HASH_MD5) { return sprintf("*%s*%s", $salt, md5($password . $salt)); } else { if ($method == self::PASSWORD_HASH_SSHA) { return sprintf("*%s*{SSHA}%s", $salt, base64_encode(sha1($password . $salt, true) . $salt)); } else { throw new OSS_Exception('Hash password method is unknown'); } } } }
public function setupAction() { if ($this->getD2EM()->getRepository('\\Entities\\Admin')->getCount() != 0) { $this->addMessage(_("Admins already exist in the system."), OSS_Message::INFO); $this->_redirect('auth/login'); } if ($this->getAuth()->getIdentity()) { $this->addMessage(_('You are already logged in.'), OSS_Message::INFO); $this->_redirect('domain/list'); } $this->view->form = $form = new ViMbAdmin_Form_Admin_AddEdit(); $form->removeElement('active'); $form->removeElement('super'); $form->removeElement('welcome_email'); if (!isset($this->_options['securitysalt']) || strlen($this->_options['securitysalt']) != 64) { $this->view->saltSet = false; $randomSalt = $this->view->randomSalt = OSS_String::salt(64); $form->getElement('salt')->setValue($randomSalt); $this->view->rememberSalt = OSS_String::salt(64); $this->view->passwordSalt = OSS_String::salt(64); } else { $this->view->saltSet = true; if ($this->getRequest()->isPost() && $form->isValid($_POST)) { if ($form->getElement('salt')->getValue() != $this->_options['securitysalt']) { $this->addMessage(_("Incorrect security salt provided. Please copy and paste it from the <code>application.ini</code> file."), OSS_Message::INFO); } else { $admin = new \Entities\Admin(); $admin->setUsername($form->getValue('username')); $admin->setPassword(OSS_Auth_Password::hash($form->getValue('password'), $this->_options['resources']['auth']['oss'])); $admin->setSuper(true); $admin->setActive(true); $admin->setCreated(new \DateTime()); $admin->setModified(new \DateTime()); $this->getD2EM()->persist($admin); // we need to populate the Doctine migration table $dbversion = new \Entities\DatabaseVersion(); $dbversion->setVersion(ViMbAdmin_Version::DBVERSION); $dbversion->setName(ViMbAdmin_Version::DBVERSION_NAME); $dbversion->setAppliedOn(new \DateTime()); $this->getD2EM()->persist($dbversion); $this->getD2EM()->flush(); try { $mailer = $this->getMailer(); $mailer->setSubject(_('ViMbAdmin :: Your New Administrator Account')); $mailer->addTo($admin->getUsername()); $mailer->setFrom($this->_options['server']['email']['address'], $this->_options['server']['email']['name']); $this->view->username = $admin->getUsername(); $this->view->password = $form->getValue('password'); $mailer->setBodyText($this->view->render('admin/email/new_admin.phtml')); $mailer->send(); } catch (Zend_Mail_Exception $e) { $this->addMessage(_('Could not send welcome email to the new administrator. Please ensure you have configured a mail relay server in your <code>application.ini</code>.'), OSS_Message::ALERT); } $this->addMessage(_('Your administrator account has been added. Please log in below.'), OSS_Message::SUCCESS); } if (!(isset($this->_options['skipInstallPingback']) && $this->_options['skipInstallPingback'])) { try { // Try and track new installs to see if it is worthwhile continuing development include_once APPLICATION_PATH . '/../public/PiwikTracker.php'; if (class_exists('PiwikTracker')) { if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { PiwikTracker::$URL = 'https://stats.opensolutions.ie/'; } else { PiwikTracker::$URL = 'http://stats.opensolutions.ie/'; } $piwikTracker = new PiwikTracker($idSite = 5); $piwikTracker->doTrackPageView('New V3 Install Completed'); $piwikTracker->doTrackGoal($idGoal = 2, $revenue = 1); } } catch (Exception $e) { } } $this->_redirect('auth/login'); } } }
public static function generateSalt() { return sprintf('$2a$%02d$%s', self::$_cost, OSS_String::random(22, true, true, true, '', '')); }
/** * Asks for the email and a CAPTCHA text, then sends a validation code (link) to the email address, * and then redirects to /reset-password */ public function lostPasswordAction() { $this->view->form = $form = $this->_getFormLostPassword(); $form->getElement('username')->setValue($this->_getParam('username', "")); $this->view->useCaptcha = $useCaptcha = isset($this->_options['resources']['auth']['oss']['lost_password']['use_captcha']) && $this->_options['resources']['auth']['oss']['lost_password']['use_captcha']; if ($useCaptcha) { OSS_Form_Captcha::addCaptchaElements($form); $captcha = new OSS_Captcha_Image(0, 0); $this->view->captchaId = $captcha->generate(); } if ($this->getRequest()->isPost()) { if ($useCaptcha && $this->_getParam('requestnewimage', 0)) { unset($_POST['requestnewimage']); $form->setDefaults($_POST); $form->getElement('captchatext')->setValue(""); return; } if ($form->isValid($_POST)) { if ($useCaptcha && !OSS_Captcha_Image::_isValid($this->_getParam('captchaid'), $this->_getParam('captchatext', '__'))) { $form->getElement('captchatext')->setValue('')->addError('The entered text does not match that of the image'); return; } $user = $this->getD2EM()->getRepository($this->getOptions()['resources']['auth']['oss']['entity'])->findOneByUsername($form->getValue('username')); if (!$user) { $this->addMessage('If your username was correct, then an email with a key to allow you to change your password below has been sent to you.', OSS_Message::SUCCESS); $this->redirectAndEnsureDie('auth/reset-password/un/' . urlencode($form->getValue('username'))); } // start by removing expired preferences if ($user->cleanExpiredPreferences()) { $this->getEntityManager()->flush(); } $pwdResetToken = OSS_String::random(40); try { $user->addIndexedPreference('tokens.password_reset', $pwdResetToken, '=', time() + 2 * 60 * 60, 5); } catch (OSS_Doctrine2_WithPreferences_IndexLimitException $e) { $this->addMessage('The limit of password reset tokens has been reached. Please try again later when the existing ones will expire or contact support.', OSS_Message::ERROR); $this->redirectAndEnsureDie('auth/lost-password'); } $this->getEntityManager()->flush(); $this->view->user = $user; $this->view->token = $pwdResetToken; $mailer = $this->getMailer(); $mailer->setFrom($this->getOptions()['identity']['mailer']['email'], $this->getOptions()['identity']['mailer']['name']); $mailer->addTo($user->getEmail(), $user->getFormattedName()); $mailer->setSubject($this->getOptions()['identity']['sitename'] . ' - Password Reset Information'); $this->resolveTemplate($mailer, 'lost-password'); $mailer->send(); $this->addMessage('If your username was correct, then an email with a key to allow you to change your password below has been sent to you.', OSS_Message::SUCCESS); $this->getLogger()->info(sprintf(_("%s requested a reset password token"), $user->getUsername())); $this->_redirect('auth/reset-password/username/' . urlencode($form->getValue('username'))); } } }
/** * Creates/updates/deletes the user for a contact when adding / editing a contact * * @param IXP_Form_Contact $form The form object * @param \Entities\Contact $contact The Doctrine2 entity (being edited or blank for add) * @param bool $isEdit True of we are editing an object, false otherwise */ private function _processUser($form, $contact, $isEdit) { if ($form->getValue("login")) { // the contact has a user already or one needs to be created if (!($user = $contact->getUser())) { $user = new \Entities\User(); $contact->setUser($user); $user->setCreated(new DateTime()); $user->setCreator($this->getUser()->getUsername()); // these should only be updated by CUSTADMIN on creation of a login account if ($this->getUser()->getPrivs() <= \Entities\User::AUTH_CUSTADMIN) { $user->setPrivs(\Entities\User::AUTH_CUSTUSER); $user->setPassword(OSS_Auth_Password::hash(OSS_String::random(16), $this->_options['resources']['auth']['oss'])); $user->setUsername($form->getValue("username")); } else { // if this is an admin user, let them start with no unread notes if ($form->getValue("privs") == \Entities\User::AUTH_SUPERUSER) { $user->setPreference('customer-notes.read_upto', time()); } } $this->getD2EM()->persist($user); $this->_feParams->userStatus = "created"; } $user->setCustomer($contact->getCustomer()); $user->setDisabled($form->getValue("disabled")); $user->setEmail($form->getValue("email")); $user->setLastupdated(new DateTime()); $user->setLastupdatedby($this->getUser()->getId()); // SUPERADMIN can update these always if ($this->getUser()->getPrivs() == \Entities\User::AUTH_SUPERUSER) { if ($form->getValue("password", '') != '') { $user->setPassword(OSS_Auth_Password::hash($form->getValue("password"), $this->_options['resources']['auth']['oss'])); } // ensure the username is not already taken if ($user->getUsername() != $form->getValue("username") && $this->getD2R('\\Entities\\User')->findOneBy(['username' => $form->getValue("username")])) { $this->addMessage('That username is already is use by another user', OSS_Message::ERROR); return false; } $user->setUsername($form->getValue("username")); $user->setPrivs($form->getValue("privs")); } $this->getLogger()->info("{$this->getUser()->getUsername()} created user {$user->getUsername()}"); } else { if ($contact->getUser()) { $this->_deleteUser($contact); } } return true; }
/** * Set cookies for Remember Me functionality * * The username is stored as a salted SHA1 hashed value to protect the user's username * The key is a random 40 charater string * * @param \Entitues\User $user The user enitiy * @param \Entities\RememberMe $rememberme The remember me entity with cookie details (or null to create one) */ protected function _setRememberMeCookie($user, $rememberme = null) { if ($rememberme == null) { $rememberme = new \Entities\RememberMe(); $rememberme->setUser($user); $rememberme->setCreated(new DateTime()); $rememberme->setOriginalIp($_SERVER['REMOTE_ADDR']); $rememberme->setUserhash($this->_generateCookieUserhash($user)); $this->getD2EM()->persist($rememberme); } $expire = time() + $this->_options['resources']['auth']['oss']['rememberme']['timeout']; $rememberme->setExpires(new DateTime("@{$expire}")); $rememberme->setLastUsed(new DateTime()); $rememberme->setCkey(OSS_String::random(40, true, true, true, '', '')); $this->getD2EM()->flush(); setcookie('aval', $rememberme->getUserhash(), $expire, '/', '', $this->_options['resources']['auth']['oss']['rememberme']['secure'], true); setcookie('bval', $rememberme->getCkey(), $expire, '/', '', $this->_options['resources']['auth']['oss']['rememberme']['secure'], true); }
/** * A generic password hashing method using a given configuration array * * The parameters expected in `$config` are: * * * `pwhash` - a hashing method from the `HASH_` constants in this class * * `hash_cost` - a *cost* parameter for certain hashing functions - e.g. bcrypt (defaults to 9) * * @param string $pw The plaintext password to hash * @param array $config The resources.auth.oss array from `application.ini` * @throws OSS_Exception * @return string The hashed password */ public static function hash($pw, $config) { $hash = self::HASH_UNKNOWN; if (is_array($config)) { if (!isset($config['pwhash'])) { throw new OSS_Exception('Cannot hash password without a hash method'); } $hash = $config['pwhash']; } else { $hash = $config; } if (substr($hash, 0, 8) == 'dovecot:') { return ViMbAdmin_Dovecot::password(substr($hash, 8), $pw, $config['username']); } else { if (substr($hash, 0, 6) == 'crypt:') { $indicator = ''; $salt_len = 2; switch ($hash) { case 'crypt:md5': $salt = '$1$' . OSS_String::randomPassword(12) . '$'; break; case 'crypt:blowfish': $salt = '$2a$12$' . OSS_String::randomPassword(22) . '$'; break; case 'crypt:sha256': $salt = '$5$' . OSS_String::randomPassword(16) . '$'; break; case 'crypt:sha512': $salt = '$6$' . OSS_String::randomPassword(12) . '$'; break; default: throw new OSS_Exception('Unknown crypt password hashing method'); } return crypt($pw, $salt); } else { switch ($hash) { case self::HASH_PLAINTEXT: case self::HASH_PLAIN: return $pw; break; case self::HASH_BCRYPT: if (!isset($config['hash_cost'])) { $config['hash_cost'] = 9; } $bcrypt = new OSS_Crypt_Bcrypt($config['hash_cost']); return $bcrypt->hash($pw); break; case self::HASH_MD5: return md5($pw); break; case self::HASH_MD5_SALTED: return md5($pw . $config['pwhash']); break; case self::HASH_SHA1: return sha1($pw); break; case self::HASH_SHA1_SALTED: return sha1($pw . $config['pwhash']); break; // UPDATE PHPDOC ABOVE WHEN ADDING NEW METHODS! // UPDATE PHPDOC ABOVE WHEN ADDING NEW METHODS! default: throw new OSS_Exception('Unknown password hashing method'); } } } }
/** * @param IXP_Form_Interface_Vlan $form The form object * @param \Entities\VlanInterface $object The Doctrine2 entity (being edited or blank for add) * @param bool $isEdit True of we are editing an object, false otherwise * @param array $options Options passed onto Zend_Form * @param string $cancelLocation Where to redirect to if 'Cancal' is clicked * @return void */ protected function formPostProcess($form, $object, $isEdit, $options = null, $cancelLocation = null) { if ($isEdit) { $form->getElement('virtualinterfaceid')->setValue($object->getVirtualInterface()->getId()); $form->getElement('preselectCustomer')->setValue($object->getVirtualInterface()->getCustomer()->getId()); $form->getElement('vlanid')->setValue($object->getVlan()->getId()); $form->getElement('preselectIPv4Address')->setValue($object->getIPv4Address() ? $object->getIPv4Address()->getAddress() : null); $form->getElement('preselectIPv6Address')->setValue($object->getIPv6Address() ? $object->getIPv6Address()->getAddress() : null); $form->getElement('preselectVlanInterface')->setValue($object->getId()); if ($this->getParam('rtn', false) == 'vli') { $form->setAction(OSS_Utils::genUrl('vlan-interface', 'edit', false, ['id' => $object->getId(), 'rtn' => 'vli'])); } else { $form->getElement('cancel')->setAttrib('href', OSS_Utils::genUrl('virtual-interface', 'edit', false, ['id' => $object->getVirtualInterface()->getId()])); } } else { if ($this->getRequest()->isPost() && ($vintid = isset($_POST['virtualinterfaceid']) && $_POST['virtualinterfaceid'])) { $vint = $this->getD2EM()->getRepository('\\Entities\\VirtualInterface')->find($_POST['virtualinterfaceid']); } else { if (($vintid = $this->getRequest()->getParam('vintid')) !== null) { $vint = $this->getD2EM()->getRepository('\\Entities\\VirtualInterface')->find($vintid); } } if (!isset($vint) || !$vint) { $this->addMessage('You need a containing virtual interface before you add a VLAN interface', OSS_Message::ERROR); $this->redirect('virtual-interface/add'); } // make BGP MD5 easy $form->getElement('ipv4bgpmd5secret')->setValue(OSS_String::random()); $form->getElement('ipv6bgpmd5secret')->setValue($form->getElement('ipv4bgpmd5secret')->getValue()); $form->getElement('maxbgpprefix')->setValue($vint->getCustomer()->getMaxprefixes()); $form->getElement('virtualinterfaceid')->setValue($vint->getId()); $form->getElement('preselectCustomer')->setValue($vint->getCustomer()->getId()); $form->getElement('cancel')->setAttrib('href', OSS_Utils::genUrl('virtual-interface', 'edit', false, ['id' => $vint->getId()])); } }