Exemplo n.º 1
0
 /**
  * Checks if the GPG key is a valid key
  * But also import it in the keychain.
  */
 public function validateGpgkey($check)
 {
     // LATER first remove the old gpgkey from the keychain
     // empty value
     if (empty($check['gpgkey'])) {
         return true;
     }
     // we have a clean, hopefull public, key here
     // key is entered
     require_once 'Crypt/GPG.php';
     try {
         $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir')));
         try {
             $keyImportOutput = $gpg->importKey($check['gpgkey']);
             if (!empty($keyImportOutput['fingerprint'])) {
                 return true;
             }
         } catch (Exception $e) {
             //debug($e);
             $this->log($e->getMessage());
             return false;
         }
     } catch (Exception $e) {
         //debug($e);
         $this->log($e->getMessage());
         return true;
         // TODO was false
     }
 }
Exemplo n.º 2
0
function verifyPGPKey($content, $email)
{
    global $config;
    //allow blank "keys" if this is set
    //this means that encryption for $email will be disabled by the cron if it
    // was enabled originally
    if ($config['pgpverify_allowblank'] && trim($content) == '') {
        return true;
    }
    require_once "Crypt/GPG.php";
    //try to create a random subdirectory of $config['pgpverify_tmpdir']
    do {
        $path = $config['pgpverify_tmpdir'] . '/' . uid(16);
    } while (file_exists($path));
    $result = @mkdir($path);
    if ($result === false) {
        if ($config['debug']) {
            die("Failed to create directory [" . $path . "] for PGP verification.");
        } else {
            return false;
        }
    }
    $gpg = new Crypt_GPG(array('homedir' => $path));
    //import the key to our GPG temp directory
    try {
        $gpg->importKey($content);
    } catch (Crypt_GPG_NoDataException $e) {
        //user supplied an invalid key!
        recursiveDelete($path);
        return false;
    }
    //verify the email address matches
    $keys = $gpg->getKeys();
    if (count($keys) != 1) {
        if ($config['debug']) {
            die("Error in PGP verification: key count is " . count($keys) . "!");
        } else {
            recursiveDelete($path);
            return false;
        }
    }
    $userIds = $keys[0]->getUserIds();
    if (count($userIds) != 1 || strtolower($userIds[0]->getEmail()) != strtolower($email)) {
        recursiveDelete($path);
        return false;
    }
    recursiveDelete($path);
    return true;
}
 /**
  * Encode file for email, encryption results in ASCII armored data which removed need for base 64 encoding step.
  *
  * @todo  test with filename instead of array passed as $file, see Email::attachFile() and ::attachFileFromString()
  * @todo  test with $destFilename
  * @todo  test with disposition set to inline
  * @todo  test with contentLocation param, see Mailer::encodeFileForEmail()
  * 
  * @param  mixed   $file         Array of file data including content or just string indicating filename
  * @param  string  $destFileName Destination filename
  * @param  string  $disposition  Disposition of attachment, inline or attachment
  * @param  string  $extraHeaders Extra headers for attachement
  * @return string                Contents for attachement including headers and ASCII armored file content
  */
 public function encodeFileForEmail($file, $destFileName = false, $disposition = NULL, $extraHeaders = "")
 {
     if (!$file) {
         user_error("encodeFileForEmail: not passed a filename and/or data", E_USER_WARNING);
         return;
     }
     if (is_string($file)) {
         $file = array('filename' => $file);
         $fh = fopen($file['filename'], "rb");
         if ($fh) {
             $file['contents'] = "";
             while (!feof($fh)) {
                 $file['contents'] .= fread($fh, 10000);
             }
             fclose($fh);
         }
     }
     // Build headers, including content type
     if (!$destFileName) {
         $base = basename($file['filename']);
     } else {
         $base = $destFileName;
     }
     // Force base and MIME type for encrypted attachements
     $base = $base . '.pgp';
     $mimeType = 'application/octet-stream';
     // TODO Need to test with contentLocation param
     if (empty($disposition)) {
         $disposition = isset($file['contentLocation']) ? 'inline' : 'attachment';
     }
     // Encode for emailing. Only accepts binary|8bit|7bit not quoted-printable|base64
     // ASCII armored output *should* be base64 though?
     $encoding = "7bit";
     // GPG encryption and signing if necessary
     if ($this->sign) {
         $file['contents'] = $this->gpg->encryptAndSign($file['contents']);
     } else {
         $file['contents'] = $this->gpg->encrypt($file['contents']);
     }
     $headers = "Content-type: {$mimeType};\n\tname=\"{$base}\"\n" . "Content-Transfer-Encoding: {$encoding}\n" . "Content-Disposition: {$disposition};\n\tfilename=\"{$base}\"\n";
     // TODO Need to test with contentLocation param
     if (isset($file['contentLocation'])) {
         $headers .= 'Content-Location: ' . $file['contentLocation'] . "\n";
     }
     $headers .= $extraHeaders . "\n";
     return $headers . $file['contents'];
 }
Exemplo n.º 4
0
 public function gpgDiagnostics(&$diagnostic_errors)
 {
     $gpgStatus = 0;
     if (Configure::read('GnuPG.email') && Configure::read('GnuPG.homedir')) {
         $continue = true;
         try {
             require_once 'Crypt/GPG.php';
             $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir'), 'binary' => Configure::read('GnuPG.binary') ? Configure::read('GnuPG.binary') : '/usr/bin/gpg'));
             $key = $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
         } catch (Exception $e) {
             $gpgStatus = 2;
             $continue = false;
         }
         if ($continue) {
             try {
                 $gpgStatus = 0;
                 $signed = $gpg->sign('test', Crypt_GPG::SIGN_MODE_CLEAR);
             } catch (Exception $e) {
                 $gpgStatus = 3;
             }
         }
     } else {
         $gpgStatus = 1;
     }
     if ($gpgStatus != 0) {
         $diagnostic_errors++;
     }
     return $gpgStatus;
 }
Exemplo n.º 5
0
 public function sendEmail($user, $body, $bodyNoEnc = false, $subject, $replyToUser = false)
 {
     $failed = false;
     $failureReason = "";
     // check if the e-mail can be encrypted
     $canEncrypt = false;
     if (isset($user['User']['gpgkey']) && !empty($user['User']['gpgkey'])) {
         $canEncrypt = true;
     }
     // If bodyonlencrypted is enabled and the user has no encryption key, use the alternate body (if it exists)
     if (Configure::read('GnuPG.bodyonlyencrypted') && !$canEncrypt && $bodyNoEnc) {
         $body = $bodyNoEnc;
     }
     $body = str_replace('\\n', PHP_EOL, $body);
     // Sign the body
     require_once 'Crypt/GPG.php';
     try {
         $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir'), 'binary' => Configure::read('GnuPG.binary') ? Configure::read('GnuPG.binary') : '/usr/bin/gpg'));
         // , 'debug' => true
         $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
         $body = $gpg->sign($body, Crypt_GPG::SIGN_MODE_CLEAR);
     } catch (Exception $e) {
         $failureReason = " the message could not be signed. The following error message was returned by gpg: " . $e->getMessage();
         $this->log($e->getMessage());
         $failed = true;
     }
     // If we cannot encrypt the mail and the server settings restricts sending unencrypted messages, return false
     if (!$failed && !$canEncrypt && Configure::read('GnuPG.onlyencrypted')) {
         $failed = true;
         $failureReason = " encrypted messages are enforced and the message could not be encrypted for this user as no valid encryption key was found.";
     }
     // Let's encrypt the message if we can
     if (!$failed && $canEncrypt) {
         $keyImportOutput = $gpg->importKey($user['User']['gpgkey']);
         try {
             $gpg->addEncryptKey($keyImportOutput['fingerprint']);
             // use the key that was given in the import
             $body = $gpg->encrypt($body, true);
         } catch (Exception $e) {
             // despite the user having a PGP key and the signing already succeeding earlier, we get an exception. This must mean that there is an issue with the user's key.
             $failureReason = " the message could not be encrypted because there was an issue with the user's PGP key. The following error message was returned by gpg: " . $e->getMessage();
             $this->log($e->getMessage());
             $failed = true;
         }
     }
     $replyToLog = '';
     if (!$failed) {
         $Email = new CakeEmail();
         // If the e-mail is sent on behalf of a user, then we want the target user to be able to respond to the sender
         // For this reason we should also attach the public key of the sender along with the message (if applicable)
         if ($replyToUser != false) {
             $Email->replyTo($replyToUser['User']['email']);
             if (!empty($replyToUser['User']['gpgkey'])) {
                 $Email->attachments(array('gpgkey.asc' => array('data' => $replyToUser['User']['gpgkey'])));
             }
             $replyToLog = 'from ' . $replyToUser['User']['email'];
         }
         $Email->from(Configure::read('MISP.email'));
         $Email->to($user['User']['email']);
         $Email->subject($subject);
         $Email->emailFormat('text');
         $result = $Email->send($body);
         $Email->reset();
     }
     $this->Log = ClassRegistry::init('Log');
     $this->Log->create();
     if (!$failed && $result) {
         $this->Log->save(array('org' => 'SYSTEM', 'model' => 'User', 'model_id' => $user['User']['id'], 'email' => $user['User']['email'], 'action' => 'email', 'title' => 'Email ' . $replyToLog . ' to ' . $user['User']['email'] . ' sent, titled "' . $subject . '".', 'change' => null));
         return true;
     } else {
         if (isset($result) && !$result) {
             $failureReason = " there was an error sending the e-mail.";
         }
         $this->Log->save(array('org' => 'SYSTEM', 'model' => 'User', 'model_id' => $user['User']['id'], 'email' => $user['User']['email'], 'action' => 'email', 'title' => 'Email ' . $replyToLog . ' to ' . $user['User']['email'] . ', titled "' . $subject . '" failed. Reason: ' . $failureReason, 'change' => null));
     }
     return false;
 }
 private function __sendProposalAlertEmail($id)
 {
     $this->loadModel('Event');
     $this->Event->recursive = -1;
     $event = $this->Event->read(null, $id);
     // If the event has an e-mail lock, return
     if ($event['Event']['proposal_email_lock'] == 1) {
         return;
     } else {
         $this->_setProposalLock($id);
     }
     try {
         $this->loadModel('User');
         $this->User->recursive = -1;
         $orgMembers = array();
         $temp = $this->User->findAllByOrg($event['Event']['orgc'], array('email', 'gpgkey', 'contactalert', 'id'));
         foreach ($temp as $tempElement) {
             if ($tempElement['User']['contactalert'] || $tempElement['User']['id'] == $event['Event']['user_id']) {
                 array_push($orgMembers, $tempElement);
             }
         }
         $body = "";
         $body .= "Hello, \n";
         $body .= "\n";
         $body .= "A user of another organisation has proposed a change to an event created by you or your organisation. \n";
         $body .= "\n";
         $body .= "To view the event in question, follow this link:";
         $body .= ' ' . Configure::read('MISP.baseurl') . '/events/view/' . $id . "\n";
         $body .= "\n";
         $body .= "You can reach the user at " . $this->Auth->user('email');
         $body .= "\n";
         // sign the body
         require_once 'Crypt/GPG.php';
         $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir'), 'binary' => Configure::read('GnuPG.binary') ? Configure::read('GnuPG.binary') : '/usr/bin/gpg'));
         $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
         $bodySigned = $gpg->sign($body, Crypt_GPG::SIGN_MODE_CLEAR);
         // Add the GPG key of the user as attachment
         // LATER sign the attached GPG key
         if (null != !$this->User->getPGP($this->Auth->user('id'))) {
             // save the gpg key to a temporary file
             $tmpfname = tempnam(TMP, "GPGkey");
             $handle = fopen($tmpfname, "w");
             fwrite($handle, $this->User->getPGP($this->Auth->user('id')));
             fclose($handle);
             // attach it
             $this->Email->attachments = array('gpgkey.asc' => $tmpfname);
         }
         foreach ($orgMembers as &$reporter) {
             if (!empty($reporter['User']['gpgkey'])) {
                 // import the key of the user into the keyring
                 // this isn't really necessary, but it gives it the fingerprint necessary for the next step
                 $keyImportOutput = $gpg->importKey($reporter['User']['gpgkey']);
                 // say what key should be used to encrypt
                 try {
                     $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir'), 'binary' => Configure::read('GnuPG.binary') ? Configure::read('GnuPG.binary') : '/usr/bin/gpg'));
                     $gpg->addEncryptKey($keyImportOutput['fingerprint']);
                     // use the key that was given in the import
                     $bodyEncSig = $gpg->encrypt($bodySigned, true);
                 } catch (Exception $e) {
                     // catch errors like expired PGP keys
                     $this->log($e->getMessage());
                     // no need to return here, as we want to send out mails to the other users if GPG encryption fails for a single user
                 }
             } else {
                 $bodyEncSig = $bodySigned;
                 // FIXME should I allow sending unencrypted "contact" mails to people if they didn't import they GPG key?
             }
             // prepare the email
             $this->Email->from = Configure::read('MISP.email');
             $this->Email->to = $reporter['User']['email'];
             $this->Email->subject = "[" . Configure::read('MISP.org') . " MISP] Proposal to event #" . $id;
             $this->Email->template = 'body';
             $this->Email->sendAs = 'text';
             // both text or html
             $this->set('body', $bodyEncSig);
             // Add the GPG key of the user as attachment
             // LATER sign the attached GPG key
             if (null != $this->User->getPGP($this->Auth->user('id'))) {
                 // attach the gpg key
                 $this->Email->attachments = array('gpgkey.asc' => $tmpfname);
             }
             // send it
             $result = $this->Email->send();
             // If you wish to send multiple emails using a loop, you'll need
             // to reset the email fields using the reset method of the Email component.
             $this->Email->reset();
         }
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
Exemplo n.º 7
0
 function run($form, $actiondata)
 {
     $email_params = new JParameter($actiondata->params);
     $email_body = $actiondata->content1;
     ob_start();
     eval("?>" . $email_body);
     $email_body = ob_get_clean();
     //build email template from defined fields and posted fields
     $replace_nulls = (bool) $email_params->get('replace_nulls', 0);
     $email_body = $form->curly_replacer($email_body, $form->data, '.', $replace_nulls);
     //add the IP if so
     if ($email_params->get('recordip', 1)) {
         if (strpos($email_body, '{IPADDRESS}') !== false) {
         } else {
             $email_body .= "<br /><br />\n\nSubmitted by {IPADDRESS}";
         }
         $email_body = str_replace('{IPADDRESS}', $_SERVER['REMOTE_ADDR'], $email_body);
     }
     if ($email_params->get('sendas', "html") == "html") {
         $email_body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n\t\t\t  <html>\n\t\t\t\t <head>\n\t\t\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n\t\t\t\t\t<base href=\"" . JURI::base() . "/\" />\n\t\t\t\t\t<title>Email</title>\n\t\t\t\t </head>\n\t\t\t\t \n\t\t\t\t <body>{$email_body}</body>\n\t\t\t  </html>";
     }
     //$fromname = (trim($email_params->get('fromname', ''))) ? trim($email_params->get('fromname', '')) : $form->data[trim($email_params->get('dfromname', ''))];
     if (trim($email_params->get('fromname', ''))) {
         $fromname = trim($email_params->get('fromname', ''));
     } else {
         if (isset($form->data[trim($email_params->get('dfromname', ''))])) {
             $fromname = $form->data[trim($email_params->get('dfromname', ''))];
         } else {
             $fromname = 'admin';
         }
     }
     //$from = (trim($email_params->get('fromemail', ''))) ? trim($email_params->get('fromemail', '')) : $form->data[trim($email_params->get('dfromemail', ''))];
     if (trim($email_params->get('fromemail', ''))) {
         $from = trim($email_params->get('fromemail', ''));
     } else {
         if (isset($form->data[trim($email_params->get('dfromemail', ''))])) {
             $from = $form->data[trim($email_params->get('dfromemail', ''))];
         } else {
             $from = '*****@*****.**';
         }
     }
     //$subject = (trim($email_params->get('subject', ''))) ? trim($email_params->get('subject', '')) : $form->data[trim($email_params->get('dsubject', ''))];
     if (trim($email_params->get('subject', ''))) {
         $subject = trim($email_params->get('subject', ''));
     } else {
         if (isset($form->data[trim($email_params->get('dsubject', ''))])) {
             $subject = $form->data[trim($email_params->get('dsubject', ''))];
         } else {
             $subject = 'DEFAULT SUBJECT';
         }
     }
     // Recepients
     $recipients = array();
     if (trim($email_params->get('to', ''))) {
         $recipients = explode(",", trim($email_params->get('to', '')));
     }
     if (trim($email_params->get('dto', ''))) {
         $dynamic_recipients = explode(",", trim($email_params->get('dto', '')));
         foreach ($dynamic_recipients as $dynamic_recipient) {
             if (isset($form->data[trim($dynamic_recipient)])) {
                 $recipients[] = $form->data[trim($dynamic_recipient)];
             }
         }
     }
     // CCs
     $ccemails = array();
     if (trim($email_params->get('cc', ''))) {
         $ccemails = explode(",", trim($email_params->get('cc', '')));
     }
     if (trim($email_params->get('dcc', ''))) {
         $dynamic_ccemails = explode(",", trim($email_params->get('dcc', '')));
         foreach ($dynamic_ccemails as $dynamic_ccemail) {
             if ($form->data[trim($dynamic_ccemail)]) {
                 $ccemails[] = $form->data[trim($dynamic_ccemail)];
             }
         }
     }
     // BCCs
     $bccemails = array();
     if (trim($email_params->get('bcc', ''))) {
         $bccemails = explode(",", trim($email_params->get('bcc', '')));
     }
     if (trim($email_params->get('dbcc', ''))) {
         $dynamic_bccemails = explode(",", trim($email_params->get('dbcc', '')));
         foreach ($dynamic_bccemails as $dynamic_bccemail) {
             if ($form->data[trim($dynamic_bccemail)]) {
                 $bccemails[] = $form->data[trim($dynamic_bccemail)];
             }
         }
     }
     // ReplyTo Names
     $replytonames = array();
     if (trim($email_params->get('replytoname', ''))) {
         $replytonames = explode(",", trim($email_params->get('replytoname', '')));
     }
     if (trim($email_params->get('dreplytoname', ''))) {
         $dynamic_replytonames = explode(",", trim($email_params->get('dreplytoname', '')));
         foreach ($dynamic_replytonames as $dynamic_replytoname) {
             if ($form->data[trim($dynamic_replytoname)]) {
                 $replytonames[] = $form->data[trim($dynamic_replytoname)];
             }
         }
     }
     // ReplyTo Emails
     $replytoemails = array();
     if (trim($email_params->get('replytoemail', ''))) {
         $replytoemails = explode(",", trim($email_params->get('replytoemail', '')));
     }
     if (trim($email_params->get('dreplytoemail', ''))) {
         $dynamic_replytoemails = explode(",", trim($email_params->get('dreplytoemail', '')));
         foreach ($dynamic_replytoemails as $dynamic_replytoemail) {
             if ($form->data[trim($dynamic_replytoemail)]) {
                 $replytoemails[] = $form->data[trim($dynamic_replytoemail)];
             }
         }
     }
     // Replies
     $replyto_email = $replytoemails;
     $replyto_name = $replytonames;
     $mode = $email_params->get('sendas', "html") == 'html' ? true : false;
     if (!$mode) {
         $filter = JFilterInput::getInstance();
         if ($email_params->get('sendas', "html") == 'both') {
             $email_body = "<!--" . $filter->clean($email_body, 'STRING') . "-->" . "\n\n\n" . $email_body;
         } else {
             $email_body = $filter->clean($email_body, 'STRING');
         }
     } else {
         //$email_body = nl2br($email_body);
     }
     //encrypt the email
     if ($email_params->get('encrypt_enabled', 0) == 1 && class_exists('Crypt_GPG')) {
         $mySecretKeyId = trim($email_params->get('gpg_sec_key', ''));
         //Add Encryption key here
         $gpg = new Crypt_GPG();
         $gpg->addEncryptKey($mySecretKeyId);
         $email_body = $gpg->encrypt($email_body);
     }
     $email_attachments = array();
     if (strlen(trim($email_params->get("attachments", ""))) && !empty($form->files)) {
         $attachments = explode(",", $email_params->get("attachments", ""));
         foreach ($attachments as $attachment) {
             if (isset($form->files[$attachment])) {
                 $email_attachments[] = $form->files[$attachment]['path'];
             }
         }
     }
     $email_sent = JUtility::sendMail($from, $fromname, $recipients, $subject, $email_body, $mode, $ccemails, $bccemails, $email_attachments, $replyto_email, $replyto_name);
     if ($email_sent) {
         $form->debug['email'][$actiondata->order]['Result'] = 'An email has been SENT successfully from (' . $fromname . ')' . $from . ' to ' . implode(',', $recipients);
     } else {
         $form->debug['email'][$actiondata->order]['Result'] = 'An email has failed to be sent from (' . $fromname . ')' . $from . ' to ' . implode(',', $recipients);
     }
     $form->debug['email'][$actiondata->order]['Body'] = $email_body;
     $form->debug['email'][$actiondata->order]['Attachments'] = var_export($email_attachments, true);
 }
Exemplo n.º 8
0
 public function testSetEngine()
 {
     $engine = new Crypt_GPG_Engine($this->getOptions());
     $gpg = new Crypt_GPG();
     $gpg->setEngine($engine);
     $homedirConstraint = $this->attribute($this->attributeEqualTo('_homedir', __DIR__ . '/' . self::HOMEDIR), 'engine');
     $this->assertThat($gpg, $homedirConstraint, 'Engine was not set properly.');
 }
Exemplo n.º 9
0
 /**
  * Decrypt and verify given string
  * 
  * @param string $string
  * @param string $keyPassword
  * @param string $keyID
  * @return array|false
  */
 public static function decryptAndVerify($string, $keyPassword = null, $keyID = null)
 {
     $gpg = new Crypt_GPG();
     if ($keyID === null) {
         $keyID = ConfigManager::getConfig("Crypto", "GPG")->AuxConfig->defaultKey;
     }
     if ($keyPassword === null) {
         $keyPassword = ConfigManager::getConfig("Crypto", "GPG")->AuxConfig->defaultKeyPasswd;
     }
     $gpg->addDecryptKey($keyID, $keyPassword);
     $result = $gpg->decryptAndVerify($string);
     if (empty($result['data']) and empty($result['signatures'])) {
         return false;
     }
     if (isset($result['signatures'][0])) {
         $result['signature'] = $result['signatures'][0]->isValid();
         unset($result['signatures']);
     }
     return $result;
 }
Exemplo n.º 10
0
 /**
  *
  * Sends out an email to all people within the same org
  * with the request to be contacted about a specific event.
  * @todo move __sendContactEmail($id, $message) to a better place. (components?)
  *
  * @param unknown_type $id The id of the event for wich you want to contact the org.
  * @param unknown_type $message The custom message that will be appended to the email.
  * @param unknown_type $all, true: send to org, false: send to person.
  *
  * @codingStandardsIgnoreStart
  * @throws \UnauthorizedException as well. // TODO Exception NotFoundException
  * @codingStandardsIgnoreEnd
  *
  * @return True if success, False if error
  */
 private function __sendContactEmail($id, $message, $all)
 {
     // fetch the event
     $event = $this->Event->read(null, $id);
     $this->loadModel('User');
     if (!$all) {
         //Insert extra field here: alertOrg or something, then foreach all the org members
         //limit this array to users with contactalerts turned on!
         $orgMembers = array();
         $this->User->recursive = 0;
         $temp = $this->User->findAllByOrg($event['Event']['org'], array('email', 'gpgkey', 'contactalert', 'id'));
         foreach ($temp as $tempElement) {
             if ($tempElement['User']['contactalert'] || $tempElement['User']['id'] == $event['Event']['user_id']) {
                 array_push($orgMembers, $tempElement);
             }
         }
     } else {
         $orgMembers = $this->User->findAllById($event['Event']['user_id'], array('email', 'gpgkey'));
     }
     // The mail body, h() is NOT needed as we are sending plain-text mails.
     $body = "";
     $body .= "Hello, \n";
     $body .= "\n";
     $body .= "Someone wants to get in touch with you concerning a MISP event. \n";
     $body .= "\n";
     $body .= "You can reach him at " . $this->Auth->user('email') . "\n";
     if (!$this->Auth->user('gpgkey')) {
         $body .= "His GPG/PGP key is added as attachment to this email. \n";
     }
     $body .= "\n";
     $body .= "He wrote the following message: \n";
     $body .= $message . "\n";
     $body .= "\n";
     $body .= "\n";
     $body .= "The event is the following: \n";
     // print the event in mail-format
     // LATER place event-to-email-layout in a function
     $appendlen = 20;
     $body .= 'URL		 : ' . Configure::read('CyDefSIG.baseurl') . '/events/view/' . $event['Event']['id'] . "\n";
     $body .= 'Event	   : ' . $event['Event']['id'] . "\n";
     $body .= 'Date		: ' . $event['Event']['date'] . "\n";
     if ('true' == Configure::read('CyDefSIG.showorg')) {
         $body .= 'Reported by : ' . $event['Event']['org'] . "\n";
     }
     $body .= 'Risk		: ' . $event['Event']['risk'] . "\n";
     $body .= 'Analysis  : ' . $event['Event']['analysis'] . "\n";
     $relatedEvents = $this->Event->getRelatedEvents($this->Auth->user());
     if (!empty($relatedEvents)) {
         foreach ($relatedEvents as &$relatedEvent) {
             $body .= 'Related to  : ' . Configure::read('CyDefSIG.baseurl') . '/events/view/' . $relatedEvent['Event']['id'] . ' (' . $relatedEvent['Event']['date'] . ')' . "\n";
         }
     }
     $body .= 'Info  : ' . "\n";
     $body .= $event['Event']['info'] . "\n";
     $body .= "\n";
     $body .= 'Attributes  :' . "\n";
     $bodyTempOther = "";
     if (!empty($event['Attribute'])) {
         foreach ($event['Attribute'] as &$attribute) {
             $line = '- ' . $attribute['type'] . str_repeat(' ', $appendlen - 2 - strlen($attribute['type'])) . ': ' . $attribute['value'] . "\n";
             if ('other' == $attribute['type']) {
                 // append the 'other' attribute types to the bottom.
                 $bodyTempOther .= $line;
             } else {
                 $body .= $line;
             }
         }
     }
     $body .= "\n";
     $body .= $bodyTempOther;
     // append the 'other' attribute types to the bottom.
     // sign the body
     require_once 'Crypt/GPG.php';
     $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir')));
     // , 'debug' => true
     $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
     $bodySigned = $gpg->sign($body, Crypt_GPG::SIGN_MODE_CLEAR);
     // Add the GPG key of the user as attachment
     // LATER sign the attached GPG key
     if ($this->Auth->user('gpgkey') != null) {
         // save the gpg key to a temporary file
         $tmpfname = tempnam(TMP, "GPGkey");
         $handle = fopen($tmpfname, "w");
         fwrite($handle, $this->Auth->user('gpgkey'));
         fclose($handle);
         // attach it
         $this->Email->attachments = array('gpgkey.asc' => $tmpfname);
     }
     foreach ($orgMembers as &$reporter) {
         if (!empty($reporter['User']['gpgkey'])) {
             // import the key of the user into the keyring
             // this isn't really necessary, but it gives it the fingerprint necessary for the next step
             $keyImportOutput = $gpg->importKey($reporter['User']['gpgkey']);
             // say what key should be used to encrypt
             try {
                 $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir')));
                 $gpg->addEncryptKey($keyImportOutput['fingerprint']);
                 // use the key that was given in the import
                 $bodyEncSig = $gpg->encrypt($bodySigned, true);
             } catch (Exception $e) {
                 // catch errors like expired PGP keys
                 $this->log($e->getMessage());
                 // no need to return here, as we want to send out mails to the other users if GPG encryption fails for a single user
             }
         } else {
             $bodyEncSig = $bodySigned;
             // FIXME should I allow sending unencrypted "contact" mails to people if they didn't import they GPG key?
         }
         // prepare the email
         $this->Email->from = Configure::read('CyDefSIG.email');
         $this->Email->replyTo = $this->Auth->user('email');
         $this->Email->to = $reporter['User']['email'];
         $this->Email->subject = "[" . Configure::read('CyDefSIG.org') . " " . Configure::read('CyDefSIG.name') . "] Need info about event " . $id . " - TLP Amber";
         //$this->Email->delivery = 'debug';   // do not really send out mails, only display it on the screen
         $this->Email->template = 'body';
         $this->Email->sendAs = 'text';
         // both text or html
         $this->set('body', $bodyEncSig);
         // Add the GPG key of the user as attachment
         // LATER sign the attached GPG key
         if ($this->Auth->user('gpgkey') != null) {
             // attach the gpg key
             $this->Email->attachments = array('gpgkey.asc' => $tmpfname);
         }
         // send it
         $result = $this->Email->send();
         // If you wish to send multiple emails using a loop, you'll need
         // to reset the email fields using the reset method of the Email component.
         $this->Email->reset();
     }
     // remove the temporary gpg file
     if ($this->Auth->user('gpgkey') != null) {
         unlink($tmpfname);
     }
     return $result;
 }
Exemplo n.º 11
0
 public function admin_email()
 {
     if (!$this->_isSiteAdmin()) {
         throw new MethodNotAllowedException();
     }
     $this->User->recursive = 0;
     $temp = $this->User->find('all', array('fields' => array('email', 'gpgkey')));
     $emails = array();
     $gpgKeys = array();
     // save all the emails of the users and set it for the dropdown list in the form
     foreach ($temp as $user) {
         array_push($emails, $user['User']['email']);
         array_push($gpgKeys, $user['User']['gpgkey']);
     }
     $this->set('recipientEmail', $emails);
     // User has filled in his contact form, send out the email.
     if ($this->request->is('post') || $this->request->is('put')) {
         $message1 = null;
         $message2 = null;
         $recipients = array();
         $messageP = array();
         // Formulating the message and the subject that will be common to the e-mail(s) sent
         if ($this->request->data['User']['action'] == '0') {
             // Custom message
             $subject = $this->request->data['User']['subject'];
             $message1 .= $this->request->data['User']['message'];
         } else {
             // Temp password
             if ($this->request->data['User']['customMessage']) {
                 $message1 .= $this->request->data['User']['message'];
             } else {
                 $message1 .= "Dear MISP user,\n\nA password reset has been triggered for your account. Use the below provided temporary password to log into MISP at ";
                 $message1 .= Configure::read('CyDefSIG.baseurl');
                 $message1 .= ", where you will be prompted to manually change your password to something of your own choice.";
             }
             //$message .= "\n\nYour temporary password: "******"\n\nIf you have any questions, contact us at: " . Configure::read('CyDefSIG.contact') . ".";
         }
         $message2 .= "\n\nBest Regards,\n" . Configure::read('CyDefSIG.org') . ' MISP support';
         // Return an error message if the action is a password reset for a new user
         if ($this->request->data['User']['recipient'] == 2 && $this->request->data['User']['action'] == '1') {
             $this->Session->setFlash(__('Cannot reset the password of a user that doesn\'t exist.'));
             $this->redirect(array('action' => 'email', 'admin' => true));
         }
         // Setting up the list of recipient(s) based on the setting and creating the final message for each user, including the password
         // If the recipient is all users, and the action to create a password, create it and for each user and squeeze it between the main message and the signature
         if ($this->request->data['User']['recipient'] == 0) {
             $recipients = $emails;
             $recipientGPG = $gpgKeys;
             if ($this->request->data['User']['action'] == '1') {
                 $i = 0;
                 foreach ($recipients as $rec) {
                     $password = $this->User->generateRandomPassword();
                     $messageP = "\n\nYour temporary password: "******"\n\nYour temporary password: " . $password . $message2;
                 $recipientPass[0] = $password;
             } else {
                 $message[0] = $message1;
             }
         }
         require_once 'Crypt/GPG.php';
         $i = 0;
         foreach ($recipients as $recipient) {
             if (!empty($recipientGPG[$i])) {
                 $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir')));
                 // , 'debug' => true
                 $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
                 $messageSigned = $gpg->sign($message[$i], Crypt_GPG::SIGN_MODE_CLEAR);
                 $keyImportOutput = $gpg->importKey($recipientGPG[$i]);
                 try {
                     $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir')));
                     $gpg->addEncryptKey($keyImportOutput['fingerprint']);
                     // use the key that was given in the import
                     $encryptedMessage = $gpg->encrypt($messageSigned, true);
                 } catch (Exception $e) {
                     // catch errors like expired PGP keys
                     $this->log($e->getMessage());
                     // no need to return here, as we want to send out mails to the other users if GPG encryption fails for a single user
                 }
             } else {
                 $encryptedMessage = $message[$i];
             }
             // prepare the email
             $this->Email->from = Configure::read('CyDefSIG.email');
             $this->Email->to = $recipients[$i];
             $this->Email->subject = $subject;
             //$this->Email->delivery = 'debug';   // do not really send out mails, only display it on the screen
             $this->Email->template = 'body';
             $this->Email->sendAs = 'text';
             // both text or html
             $this->set('body', $encryptedMessage);
             // send it
             $result = $this->Email->send();
             // if sending successful and action was a password change, update the user's password.
             if ($result && $this->request->data['User']['action'] == '1') {
                 $this->User->recursive = 0;
                 $temp = $this->User->findByEmail($recipients[$i]);
                 $this->User->id = $temp['User']['id'];
                 $this->User->read();
                 $this->User->saveField('password', $recipientPass[$i]);
                 $this->User->saveField('change_pw', '1');
             }
             // If you wish to send multiple emails using a loop, you'll need
             // to reset the email fields using the reset method of the Email component.
             $this->Email->reset();
             $i++;
         }
         $this->Session->setFlash(__('E-mails sent.'));
     }
     // User didn't see the contact form yet. Present it to him.
 }
Exemplo n.º 12
0
$in = fopen('php://stdin', 'r');
while (!feof($in)) {
    $raw = $raw . fgets($in, 4096);
}
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$decoder = new Mail_mimeDecode($raw);
$structure = $decoder->decode($params);
foreach ($argv as $recipient) {
    $encrypted = strpos($structure->body, '-----BEGIN PGP');
    if ($structure->ctype_secondary === 'encrypted' || $encrypted !== false) {
        /* Already encrypted. We don't touch. */
        $newBody = getBody($raw);
    } else {
        $gpg = new Crypt_GPG(array('homedir' => $config['gpg']['home']));
        $userKeyId = getUserKeyId($dbh, $recipient);
        $availableKeys = $gpg->getKeys($userKeyId);
        if (sizeof($availableKeys) == 1) {
            $gpg->addEncryptKey($userKeyId);
            /* Step 1. Change content type. */
            $structure->headers['content-type'] = 'multipart/encrypted; protocol="application/pgp-encrypted"; boundary="MfFXiAuoTsnnDAfX"';
            /*Step 1.5. Remove headers we don't need. */
            unset($structure->headers['content-transfer-encoding']);
            unset($structure->headers['x-google-sender-auth']);
            /* Step 2. Encrypt. */
            $newBody = 'This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)' . "\n";
            $newBody .= '--MfFXiAuoTsnnDAfX' . "\n";
            $newBody .= 'Content-Type: application/pgp-encrypted' . "\n";
            $newBody .= 'Content-Disposition: attachment' . "\n";
            $newBody .= '' . "\n";
Exemplo n.º 13
0
 /**
  * Verify a message
  *
  * @param Message $message
  * @param string $fingerprint
  * @return bool
  * @throws \Exception
  */
 public function verify(Message $message, string $fingerprint) : bool
 {
     $gnupg = new \Crypt_GPG($this->options);
     $gnupg->addSignKey($fingerprint);
     /**
      * @var \Crypt_GPG_Signature[]
      */
     $verified = $gnupg->verify($message->getBodyText());
     foreach ($verified as $sig) {
         if (false) {
             $sig = new \Crypt_GPG_Signature();
         }
         if ($sig->isValid()) {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 14
0
 function execute(&$form, $action_id)
 {
     $config = $form->actions_config[$action_id];
     $config = new \GCore\Libs\Parameter($config);
     ob_start();
     eval('?>' . $config->get('template', ''));
     $body = ob_get_clean();
     $others = array();
     //get recipient
     $tos = array();
     if (strlen(trim($config->get('to', '')))) {
         $tos = explode(',', \GCore\Libs\Str::replacer(trim($config->get('to', '')), $form->data));
     }
     if (strlen(trim($config->get('dto', '')))) {
         $dtos = explode(',', trim($config->get('dto', '')));
         foreach ($dtos as $dto) {
             $d_email = explode(',', $form->data($dto));
             $tos = array_merge((array) $d_email, $tos);
         }
     }
     $ccs = array();
     if (strlen(trim($config->get('cc', '')))) {
         $ccs = explode(',', \GCore\Libs\Str::replacer(trim($config->get('cc', '')), $form->data));
     }
     if (strlen(trim($config->get('dcc', '')))) {
         $dccs = explode(',', trim($config->get('dcc', '')));
         foreach ($dccs as $dcc) {
             $d_email = explode(',', $form->data($dcc));
             $ccs = array_merge((array) $d_email, $ccs);
         }
     }
     $others['cc'] = $ccs;
     $bccs = array();
     if (strlen(trim($config->get('bcc', '')))) {
         $bccs = explode(',', \GCore\Libs\Str::replacer(trim($config->get('bcc', '')), $form->data));
     }
     if (strlen(trim($config->get('dbcc', '')))) {
         $dbccs = explode(',', trim($config->get('dbcc', '')));
         foreach ($dbccs as $dbcc) {
             $d_email = explode(',', $form->data($dbcc));
             $bccs = array_merge((array) $d_email, $bccs);
         }
     }
     $others['bcc'] = $bccs;
     //subject
     $subject = trim($config->get('subject', '')) ? \GCore\Libs\Str::replacer($config->get('subject', ''), $form->data) : $form->data($config->get('dsubject', ''));
     //from
     $others['from_name'] = trim($config->get('from_name', '')) ? \GCore\Libs\Str::replacer($config->get('from_name', ''), $form->data) : $form->data($config->get('dfrom_name'), null);
     $others['from_email'] = trim($config->get('from_email', '')) ? \GCore\Libs\Str::replacer($config->get('from_email', ''), $form->data) : $form->data($config->get('dfrom_email'), null);
     //reply to
     $others['reply_name'] = trim($config->get('reply_name', '')) ? \GCore\Libs\Str::replacer($config->get('reply_name', ''), $form->data) : $form->data($config->get('dreply_name'), null);
     $others['reply_email'] = trim($config->get('reply_email', '')) ? \GCore\Libs\Str::replacer($config->get('reply_email', ''), $form->data) : $form->data($config->get('dreply_email'), null);
     $others['type'] = $config->get('email_type', 'html');
     $form->data['ip_address'] = $_SERVER['REMOTE_ADDR'];
     if ($others['type'] == 'html') {
         if ($config->get('append_ip_address', 1)) {
             $body = $body . "<br /><br />" . "IP: {ip_address}";
         }
         $body = \GCore\Libs\Str::replacer($body, $form->data, array('replace_null' => true, 'nl2br' => true, 'repeater' => 'repeater'));
     } else {
         if ($config->get('append_ip_address', 1)) {
             $body = $body . "\n\n" . "IP: {ip_address}";
         }
         $body = \GCore\Libs\Str::replacer($body, $form->data, array('replace_null' => true, 'repeater' => 'repeater'));
     }
     //attach
     $attachments = array();
     if (strlen(trim($config->get('attach', '')))) {
         ob_start();
         $attach_fields = eval('?>' . trim($config->get('attach', '')));
         ob_end_clean();
         if (is_array($attach_fields)) {
             $attachs = array_keys($attach_fields);
             foreach ($form->files as $name => $file) {
                 if (in_array($name, $attachs)) {
                     if (\GCore\Libs\Arr::is_assoc($file)) {
                         $attachments[] = array_merge($attach_fields[$name], array('path' => $file['path']));
                     } else {
                         foreach ($file as $fi => $fv) {
                             //$attachments[] = $fv['path'];
                             $attachments[] = array_merge($attach_fields[$name], array('path' => $fv['path']));
                         }
                     }
                 }
             }
         } else {
             $attachs = explode(',', trim($config->get('attach', '')));
             foreach ($form->files as $name => $file) {
                 if (in_array($name, $attachs)) {
                     if (\GCore\Libs\Arr::is_assoc($file)) {
                         $attachments[] = $file['path'];
                     } else {
                         foreach ($file as $fi => $fv) {
                             $attachments[] = $fv['path'];
                         }
                     }
                 }
             }
         }
     }
     //load global settings
     $settings = $form::_settings();
     if (!empty($settings['mail'])) {
         if (!empty($settings['mail']['smtp']) and empty($settings['mail']['mail_method'])) {
             $settings['mail']['mail_method'] = 'smtp';
         }
         foreach ($settings['mail'] as $k => $v) {
             \GCore\Libs\Base::setConfig($k, $v);
         }
     }
     //encrypt the email
     if ($config->get('encrypt_enabled', 0) == 1 and class_exists('Crypt_GPG')) {
         $mySecretKeyId = trim($config->get('gpg_sec_key', ''));
         //Add Encryption key here
         $gpg = new Crypt_GPG();
         $gpg->addEncryptKey($mySecretKeyId);
         $body = $gpg->encrypt($body);
     }
     $sent = \GCore\Libs\Mailer::send($tos, $subject, $body, $attachments, $others);
     if ($sent) {
         $form->debug[$action_id][self::$title][] = "An email with the details below was sent successfully:";
     } else {
         $form->debug[$action_id][self::$title][] = "An email with the details below could NOT be sent:";
     }
     $form->debug[$action_id][self::$title][] = "To:" . implode(", ", $tos);
     $form->debug[$action_id][self::$title][] = "Subject:" . $subject;
     $form->debug[$action_id][self::$title][] = "From name:" . $others['from_name'];
     $form->debug[$action_id][self::$title][] = "From email:" . $others['from_email'];
     $form->debug[$action_id][self::$title][] = "CC:" . implode(", ", $ccs);
     $form->debug[$action_id][self::$title][] = "BCC:" . implode(", ", $bccs);
     $form->debug[$action_id][self::$title][] = "Reply name:" . $others['reply_name'];
     $form->debug[$action_id][self::$title][] = "Reply email:" . $others['reply_email'];
     $form->debug[$action_id][self::$title][] = "Attachments:";
     $form->debug[$action_id][self::$title][] = $attachments;
     $form->debug[$action_id][self::$title][] = "Body:\n" . $body;
 }
Exemplo n.º 15
0
<?php

use Symfony\Component\HttpFoundation\Request;
use Webguerilla\Form\ContactForm;
$form = $app['form.factory']->create(new ContactForm());
$app->get('/', function () use($app, $form) {
    return $app['twig']->render('homepage.html', array('form' => $form->createView()));
});
$app->post('/', function (Request $request) use($app, $form, $config) {
    $form->handleRequest($request);
    if ($form->isValid()) {
        $data = $form->getData();
        $gpg = new Crypt_GPG(array('homedir' => PATH_GPG));
        $gpg->importKeyFile($config->getPublicKeyFilepath());
        $gpg->addEncryptKey($config->getEncryptionKeyID());
        $message = 'Content-Type: multipart/mixed; boundary="37ATkjK6nO8wWoV1MT91OAQPlh4P6le0q"' . "\r\n" . "\r\n" . '--37ATkjK6nO8wWoV1MT91OAQPlh4P6le0q' . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . $data['message'] . "\r\n" . "\r\n" . '--37ATkjK6nO8wWoV1MT91OAQPlh4P6le0q--' . "\r\n";
        $encryptedMessage = $gpg->encrypt($message);
        $fullEncryptedMessage = 'This is an OpenPGP/MIME encrypted message (RFC 2440 and 3156)' . "\r\n" . '--24i8m5cu37hapwm904t8v' . "\r\n" . 'Content-Type: application/pgp-encrypted' . "\r\n" . 'Content-Description: PGP/MIME version identification' . "\r\n" . "\r\n" . 'Version: 1' . "\r\n" . "\r\n" . '--24i8m5cu37hapwm904t8v' . "\r\n" . 'Content-Type: application/octet-stream; name="encrypted.asc"' . "\r\n" . 'Content-Description: OpenPGP encrypted message' . "\r\n" . 'Content-Disposition: inline; filename="encrypted.asc"' . "\r\n" . "\r\n" . $encryptedMessage . "\r\n" . '--24i8m5cu37hapwm904t8v--';
        $headers = 'From: ' . $data['name'] . ' <' . $data['email'] . '>' . "\r\n" . 'Content-Type: multipart/encrypted;' . "\r\n" . ' protocol="application/pgp-encrypted";' . "\r\n" . ' boundary="24i8m5cu37hapwm904t8v"' . "\r\n";
        // TODO randomize boundary
        if (mail($config->getMessageReceiverAddress(), $data['subject'], $fullEncryptedMessage, $headers)) {
            $app['session']->getFlashBag()->set('successfull', 'Your message has been sent successfully.');
            return $app->redirect($config->baseURL);
            // TODO
        }
    }
    return $app['twig']->render('homepage.html', array('form' => $form->createView(), 'error' => true));
});
Exemplo n.º 16
0
function verify_file($filedata, $signature)
{
    $gpg = new Crypt_GPG();
    $results = $gpg->verify($signature);
    return $results;
}