45 lines
8.1 KiB
PHP
45 lines
8.1 KiB
PHP
<?php
|
|
// Single explicit recipient authorized by the owner. No collective send, queues, secrets in reports, or flags changed.
|
|
ini_set('zend.exception_ignore_args','1');
|
|
$out=__DIR__;$stage='initial';$accountId=in_array('--account',$argv,true)?(int)($argv[array_search('--account',$argv,true)+1]??0):17;
|
|
$recipients=[14=>'aurora.chachuaio@tempo.co.mz',15=>'palmira.matsinhe@tempo.co.mz',16=>'mario.melembe@tempo.co.mz',17=>'info@tempo.co.mz'];
|
|
if(!isset($recipients[$accountId])){fwrite(STDERR,'Recipient outside explicitly authorized incident scope');exit(2);}
|
|
$recipient=$recipients[$accountId];$attemptFile=$out.'/C132-account'.$accountId.'-email-attempt.json';
|
|
if(is_file($attemptFile)){
|
|
$previous=json_decode(file_get_contents($attemptFile),true,512,JSON_THROW_ON_ERROR);
|
|
if(($argv[1]??'')!=='--retry-before-send'||($previous['stage']??'')!=='SMTP-connect-TLS-auth'||!array_key_exists('outcome_may_be_unknown',$previous)||$previous['outcome_may_be_unknown']!==false){fwrite(STDERR,'Previous attempt requires reconciliation; no message sent');exit(2);}
|
|
$archive=$out.'/C132-account17-email-before-send-failure-'.gmdate('Ymd_His').'.json';
|
|
if(!rename($attemptFile,$archive))throw new RuntimeException('Cannot preserve previous attempt');
|
|
}
|
|
set_exception_handler(function(Throwable $e)use(&$stage,$attemptFile){$safe=['at'=>gmdate('c'),'stage'=>$stage,'error_type'=>$e::class,'values_recorded'=>false,'outcome_may_be_unknown'=>$stage==='SMTP-send','automatic_retry'=>false];file_put_contents($attemptFile,json_encode($safe,JSON_PRETTY_PRINT));fwrite(STDERR,json_encode($safe));exit(1);});
|
|
$root=dirname(__DIR__,2);require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
|
|
if(is_file($attemptFile))throw new RuntimeException('Existing attempt; inspect before any resend');
|
|
$c=config('database.connections.'.config('database.default'));if($c['database']!=='investemoz'||(int)$c['port']!==5432)throw new RuntimeException('Target mismatch');
|
|
$db=new PDO('pgsql:host='.$c['host'].';port='.$c['port'].';dbname='.$c['database'],$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$db->exec('BEGIN READ ONLY');
|
|
$query=$db->prepare('SELECT id,name,email,email_verified_at,two_factor_secret FROM users WHERE id=:id');$query->execute(['id'=>$accountId]);$u=$query->fetch(PDO::FETCH_ASSOC);$db->exec('ROLLBACK');
|
|
if(!$u||strtolower($u['email'])!==$recipient||$u['email_verified_at']===null)throw new RuntimeException('Verified recipient mismatch');
|
|
$loc=json_decode(ltrim(file_get_contents($out.'/C132-private-location.json'),"\xEF\xBB\xBF"),true,512,JSON_THROW_ON_ERROR)['private_directory'];
|
|
$file=$loc.'/handoff-affected-users/conta-'.$accountId.'-2fas-local.html';$html=file_get_contents($file);if(preg_match_all('/<code>([A-Z2-7]{16,})<\/code>/',$html,$matches)!==1)throw new RuntimeException('Handoff format differs');
|
|
$key=config('app.key');$crypt=new Illuminate\Encryption\Encrypter(str_starts_with($key,'base64:')?base64_decode(substr($key,7),true):$key,config('app.cipher'));
|
|
if(!hash_equals($crypt->decrypt($u['two_factor_secret']),$matches[1][0]))throw new RuntimeException('Handoff does not match current MFA');unset($html,$matches);
|
|
$smtp=config('mail.mailers.smtp');if(empty($smtp['host'])||empty($smtp['username'])||empty($smtp['password'])||!empty($smtp['url']))throw new RuntimeException('Explicit SMTP required');
|
|
// SocketStream::isTLS describes the implicit TLS setting, not a subsequent STARTTLS negotiation.
|
|
// Inspect only negotiated cryptography metadata; never expose the SMTP debug buffer.
|
|
$transport=new Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport($smtp['host'],(int)$smtp['port'],(int)$smtp['port']===465);
|
|
$transport->setUsername($smtp['username'])->setPassword($smtp['password'])->setRequireTls(true)->setAutoTls(true);
|
|
$transport->getStream()->setTimeout(20)->setStreamOptions(['ssl'=>['verify_peer'=>true,'verify_peer_name'=>true,'allow_self_signed'=>false,'peer_name'=>$smtp['host'],'crypto_method'=>STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT|(defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT')?STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT:0)]]);
|
|
$transport->setLocalDomain($smtp['local_domain']?:'portal-investidor.test');
|
|
$from=config('mail.from');if(!filter_var($from['address'],FILTER_VALIDATE_EMAIL))throw new RuntimeException('Invalid sender');
|
|
$body="Ao gestor da conta corporativa info@tempo.co.mz,\n\nPor instrução do responsável da Tempo, enviamos individualmente a nova entrada 2FAS da conta 17 do Portal InvesteMoz ativo. O anexo pertence exclusivamente a esta conta e substitui a entrada anterior, renovada na resposta ao incidente C132. A password existente mantém-se.\n\n1. Abra o anexo localmente, num equipamento sob o seu controlo.\n2. No 2FAS Auth, adicione a nova entrada pelo QR ou pela alternativa manual do próprio anexo. Pode continuar a usar o 2FAS Auth.\n3. Na máquina onde o portal está disponível, abra https://portal-investidor.test/login, use a password própria e o código do novo autenticador; depois abra /dashboard. Não use as contas ou portas QA para esta validação.\n4. Responda apenas: conta 17 — recebido, MFA configurado e dashboard acessível; ou o texto de um erro sem dados sensíveis.\n\nO anexo contém um segredo de autenticação: mantenha-o privado e não o reencaminhe. Não responda com QR, password, segredo, código MFA ou códigos de recuperação. Após configurar, guarde os códigos de recuperação novos pelo fluxo autenticado do portal.\n\nA confirmação do gestor é necessária para registar recuperação do acesso; o envio deste email, por si só, não a comprova.\n\nTempo Lda — Portal InvesteMoz\n";
|
|
$body=str_replace(['Ao gestor da conta corporativa info@tempo.co.mz,','conta 17','conta 17 —'],['Ao titular '.$u['name'].' ('.$recipient.'),','conta '.$accountId,'conta '.$accountId.' —'],$body);
|
|
$email=(new Symfony\Component\Mime\Email())->from(new Symfony\Component\Mime\Address($from['address'],$from['name']))->to($recipient)->subject('InvesteMoz C132 — nova entrada 2FAS individual da conta '.$accountId)->text($body)->attachFromPath($file,'InvesteMoz-conta-'.$accountId.'-2FAS.html','text/html');
|
|
$email->getHeaders()->addIdHeader('Message-ID','c132-account'.$accountId.'-20261012-'.bin2hex(random_bytes(12)).'@'.substr(strrchr($from['address'],'@'),1));
|
|
$stage='SMTP-connect-TLS-auth';$transport->start();
|
|
$socket=(new ReflectionProperty(Symfony\Component\Mailer\Transport\Smtp\Stream\AbstractStream::class,'stream'))->getValue($transport->getStream());
|
|
$tls=stream_get_meta_data($socket)['crypto']??[];unset($socket);
|
|
if(empty($tls['protocol'])||!str_starts_with($tls['protocol'],'TLS'))throw new RuntimeException('TLS not established');
|
|
$stage='SMTP-send';file_put_contents($attemptFile,json_encode(['at'=>gmdate('c'),'account_id'=>$accountId,'recipient'=>$recipient,'stage'=>'SMTP-send-started','automatic_retry'=>false,'private_attachment'=>true,'values_recorded'=>false],JSON_PRETTY_PRINT));
|
|
$sent=$transport->send($email);$transport->stop();if(!$sent)throw new RuntimeException('No SMTP acceptance receipt');
|
|
$proof=['at'=>gmdate('c'),'account_id'=>$accountId,'recipient'=>$recipient,'recipient_count'=>1,'CC_BCC'=>0,'transport'=>'existing_corporate_SMTP','TLS_required_and_certificate_verified'=>true,'negotiated_TLS_protocol'=>$tls['protocol'],'SMTP_accepted'=>true,'message_id'=>$sent->getMessageId(),'private_attachment_count'=>1,'attachment_contains_secret'=>true,'attachment_or_secret_values_in_chat_or_report'=>false,'owner_authorization'=>$accountId===17?'Explicit owner reply: send email to info@tempo.co.mz, corporate manager will reply':'Explicit owner reply: send three separate emails to respective corporate addresses with mandatory TLS','mailbox_receipt_confirmed'=>false,'holder_authentication_confirmed'=>false,'notifications_flag_changed'=>false,'C131_included'=>false];
|
|
file_put_contents($attemptFile,json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));file_put_contents($out.'/C132-account'.$accountId.'-email-receipt.json',json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($proof,JSON_THROW_ON_ERROR);
|