Précédent   Forum des professionnels en informatique > PHP > Scripts
Scripts Forum d'entraide sur les scripts PHP téléchargés. Les meilleurs scripts PHP, la FAQ scripts PHP, toutes les FAQ PHP
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 07/06/2011, 14h46   #1
Membre régulier
 
Homme
Étudiant
Inscription : juin 2011
Messages : 55
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France, Val d'Oise (Île de France)

Informations professionnelles :
Activité : Étudiant
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : juin 2011
Messages : 55
Points : 77
Points : 77
Par défaut Erreur DKIM par PHPMailer

Bonjour à tous et à toutes. Nombreux sont ceux qui rencontrent des problèmes sur ce genre de technologies et les réponses ne courent pas les pages internet... Voici donc le problème que je vous énonce

Je désire, par le biais de PHPMailer, envoyé par SMTP (par un compte gmail) un mail signé par DKIM
Passant par cette messagerie et envoyant un mail directement à check-auth2@verifier.port25.com, celui ci me dit :

Code :
1
2
3
4
5
6
7
8
==========================================================
Summary of Results
==========================================================
SPF check:          pass
DomainKeys check:   pass
DKIM check:         pass
Sender-ID check:    pass
SpamAssassin check: ham

Or, lorsque j'essaye d'envoyer un mail par le biais de PHPMailer, tout d'abord en envoyant un message avec isHTML(), il me renvoit

Code :
1
2
3
4
5
----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         fail (wrong body hash: expected d9/33fwdFUC2QFjBLdJ+eUAUOkI=)
ID(s) verified:
Voici l'intégralité des données à savoir. Ma clé publique et privée sont bien liées

DNS : alpha._domainkey.mondomaine.com IN TXT :
Code :
v=DKIM1; t=y; g=*; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVZFTP7HGt2vP24vr1sbhdYD187wih1hAW9jmOw1dn6stOEd47nxEP/L6reGVhrl7bZMUZymdJAXWMF9WMAMEXq3rpxYppgZsliRMnqXv3U3a36UIL1UT+9EiicY3F/smiP2udEoXa6yVA1qaTMOmU0XjAcCAhfIr4DeHcBXjV8QIDAQAB
DKIM Signature
Code :
1
2
3
4
5
6
7
8
9
Canonicalized Headers:
   mime-version:1.0'0D''0A'
   date:Tue,'20'7'20'Jun'20'2011'20'12:25:56'20'+0200'0D''0A'
   message-id:290e94045cd61bb797269dc58ed9dd24'0D''0A'
   subject:test'0D''0A'
   from:"election@mondomaine.com"'20'<election@mondomaine.com>'0D''0A'
   to:check-auth2@verifier.port25.com'0D''0A'
   content-type:text/plain;'20'charset="iso-8859-1"'0D''0A'
   dkim-signature:v=1;'20'a=rsa-sha1;'20'q=dns/txt;'20'l=10;'20's=alpha;'20't=1307442356;'20'c=relaxed;'20'h=mime-version:x-originating-ip:date:message-id:subject:from:to:content-type;'20'd=mondomaine.com;'20'i=election@mondomaine.com;'20'z=From:=20"election@mondomaine.com"=20<election@mondomaine.com>'20'|To:=20check-auth2@verifier.port25.com'20'|Subject:=20test;'20'bh=rW0noVoasYkysD56sSWhUbVPniU=;'20'b=
Vous noterez ici que l'attribut b n'est pas renseigné alors que dans le mail original :
Code :
1
2
3
4
5
6
7
8
9
10
X-PHPMAILER-DKIM: phpmailer.worxware.com
DKIM-Signature: v=1; a=rsa-sha1; q=dns/txt; l=10; s=alpha;
       t=1307442356; c=relaxed;
       h=mime-version:x-originating-ip:date:message-id:subject:from:to:content-type;
       d=mondomaine.com; i=election@mondomaine.com;
       z=From:=20"election@mondomaine.com"=20<election@mondomaine.com>
       |To:=20check-auth2@verifier.port25.com
       |Subject:=20test;
       bh=rW0noVoasYkysD56sSWhUbVPniU=;
       b=HCjg5YB5QOfxHLHhVzwYI6jTeMtXf8t/JCLrqp/WPdgpurEr0UwVsdMNY3Byo/qik6SLJPMrUDvY58aABuIV8DJhRR3jds/ekLfMEwn1TvTfdHDM1amLiEOOW6+lAqvzUjJ5qSzWkKAauwfLg27s5N02ofXgjOgKojMfOcNwmN4=
Appel de la fonction PHP
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Envoi du mail via MySMTP.eu
   // Chargement de la bibliothèque phpmailer
      require_once("class_phpmailer/phpmailer.php5");
      require_once("class_phpmailer/smtp.php5"); 
   // Chargement des paramètres de connexion à gmail
      $mail             = new PHPMailer();
      $mail->IsSMTP();
      $mail->SMTPAuth = true;
      $account = fnct_app_constant_get('smtp_dk_login');
      $password = SMTP_PWD; // Définit en temps que constante
      $mail->Host       = '81.19.234.29';  //*'mysmtp.eu';
      $mail->Port        = 587;
      $mail->Username = $account;
      $mail->Password = $password;		 
      $mail->From       = $account;
   // Chargement des entêtes du mail
      $mail->FromName = 'election@mondomaine.com';
      $mail->Subject    = Test;
      $mail->WordWrap = 75;
      $mail->AddReplyTo($account,'election@mondomaine.com');
      $mail->AddAddress('check-auth2@verifier.port25.com');
   // Ajout de la signature DKIM
      $mail->DKIM_selector = 'alpha';
      $mail->DKIM_identity = $mail->From;
      $mail->DKIM_domain   = 'mondomaine.com';
      $mail->DKIM_private  = 'parametre/dkim_private.key'; // Fichier contenant la clé format PEM
      $mail->DKIM_passphrase = '';
   // Génération d'un identifiant de suivi
      $msgID = md5(mt_rand(0, 32).time());
      $mail->MessageID = $msgID;
   // Chargement du contenu HTML
      $html_content = '<b>Test de mail</b>';
      $mail->MsgHTML($html_content);
      $mail->AltBody = 'Test de mail';
      $mail->IsHTML(true);
      $mail->TransportId = $msgID;
 
  // Envoi du mail
      $sent = $mail->Send();
      if($sent) {
          echo "Le message a été envoyé";
      } else {
          echo "Le message n'a pas été envoyé";
      };
// Fin de la fonction
Voici donc les questions que je me pose :

1) Que dois-je modifier pour faire en sorte que ma signature passe enfin sur un mail généré par PHPMailer ?

2) Comment se fait-il que la version canonicalized des headers ne contienne pas l'attribut b, étant pourtant la signature en elle même.
Edit : en réfléchissant un peu il est logique que cet attribut soit vide. vu qu'il s'agit de la signature du header jusqu'au '... b=' il ne peut pas être pris en compte dans la canonicalization du header ou le test de la signature sera forcément faux.
Avalion est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/06/2011, 09h47   #2
Membre régulier
 
Homme
Étudiant
Inscription : juin 2011
Messages : 55
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France, Val d'Oise (Île de France)

Informations professionnelles :
Activité : Étudiant
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : juin 2011
Messages : 55
Points : 77
Points : 77
J'ai avancé ^^ Pour la question du wrong body hash modifier la fonction DKIM_BodyC est nécéssaire dans PHPMailer

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public function DKIM_BodyC($body) {
    if ($body == '') return "\r\n";
    // stabilize line endings
    $body=str_replace("\r\n","\n",$body);
    $body=str_replace("\n","\r\n",$body);
    // END stabilize line endings
    while (substr($body,strlen($body)-2,2) == "\r\n") {
      $body=substr($body,0,strlen($body)-2);
    }
    // au lieu de return $body . "\r\n";
    if ($this->ContentType == 'text/html') {
    	return "\r\n" . $body;
    } else {
        return $body . "\r\n";
    };
  }
En effet, les saut le lignes à la fin du messages sont inutiles et ne changent pas le hash. Par contre ceux au début le modifient.

Malheureusement désormais :
Code :
1
2
3
4
----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         fail (signature doesn't verify)
Mais ca je pense que c'est plutot de mon coté :s j'espère que ca pourra vous aider.
Avalion est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 09/06/2011, 12h14   #3
Membre régulier
 
Homme
Étudiant
Inscription : juin 2011
Messages : 55
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France, Val d'Oise (Île de France)

Informations professionnelles :
Activité : Étudiant
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : juin 2011
Messages : 55
Points : 77
Points : 77
Bonjour à tous. J'ai fini par résoudre mon problème tout seul.

Je vous envoie donc mes fonctions PHPMailer associées au DKIM, pour que cela fonctionne (normalement) sans problèmes. (a remplacer directement dans PHPMailer !)

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
  /**
   * Set the private key file and password to sign the message.
   *
   * @access public
   * @param string $key_filename Parameter File Name
   * @param string $key_pass Password for private key
   */
  public function DKIM_QP($txt) {
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
      $ord=ord($txt[$i]);
      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
        $line.=$txt[$i];
      } else {
        $line.="=".sprintf("%02X",$ord);
      }
    }
    return $line;
  }
 
  /**
   * Generate DKIM signature
   *
   * @access public
   * @param string $s Header
   */
  public function DKIM_Sign($s) {
    $privKeyStr = file_get_contents($this->DKIM_private);
    if ($this->DKIM_passphrase!='') {
      $privKey = openssl_pkey_get_private($privKeyStr,$this->DKIM_passphrase);
    } else {
      $privKey = openssl_pkey_get_private($privKeyStr);
    }
    if (openssl_sign($s, $signature, $privKey)) {
      return base64_encode($signature);
    }
  }
 
  /**
   * Generate DKIM Canonicalization Header
   *
   * @access public
   * @param string $s Header
   */
  public function DKIM_HeaderC($s) {
    $s=preg_replace("/\r\n\s+/"," ",$s);
    $lines=explode("\r\n",$s);
    foreach ($lines as $key=>$line) {
      list($heading,$value)=explode(":",$line,2);
      $heading=strtolower($heading);
      $value=preg_replace("/\s+/"," ",$value) ; // Compress useless spaces
      $lines[$key]=$heading.":".trim($value) ; // Don't forget to remove WSP around the value
    }
    $s=implode("\r\n",$lines);
    return $s;
  }
 
  /**
   * Generate DKIM Canonicalization Body
   *
   * @access public
   * @param string $body Message Body
   */
  public function DKIM_BodyC($body) {
    if ($body == '') return "\r\n";
    // stabilize line endings
    $body=str_replace("\r\n","\n",$body);
    $body=str_replace("\n","\r\n",$body);
    // END stabilize line endings
    while (substr($body,strlen($body)-2,2) == "\r\n") {
      $body=substr($body,0,strlen($body)-2);
    }
		sss_error_track($this->ContentType);
		if ($this->ContentType == 'text/plain') {
    	return $body . "\r\n";
		} else {
			return "\r\n" . $body;
		};
  }
 
  /**
   * Create the DKIM header, body, as new header
   *
   * @access public
   * @param string $headers_line Header lines
   * @param string $subject Subject
   * @param string $body Body
   */
  public function DKIM_Add($headers_line,$subject,$body) {
		$boundary_header 			= ''; // initialisation
    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
    $DKIMcanonicalization = 'relaxed'; // Canonicalization of header/body
    $DKIMquery            = 'dns/txt'; // Query method
    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
    $subject_header       = "Subject: $subject";
    $headers              = explode("\n",$headers_line);
    foreach($headers as $header) {
      if (strpos($header,'From:') === 0) {
        $from_header=$header;
      } elseif (strpos($header,'To:') === 0) {
        $to_header=$header;
      } elseif (strpos($header,'Message-ID:') === 0) {
				$msgid_header = $header;
			} elseif (strpos($header,'MIME-Version:') === 0) {
				$mime_header = $header;
			} elseif (strpos($header,'Date:') === 0) {
				$date_header = $header;
			} elseif (strpos($header,'Content-Type:') === 0) {
				$content_header = $header;
			} elseif (strpos($header,'boundary=') !== false) {
				$boundary_header = substr($header,strpos($header,'boundary='),strlen($header) - strpos($header,'boundary='));
			}
    }
 
    $from     = str_replace('|','=7C',$this->DKIM_QP($from_header));
    $to       = str_replace('|','=7C',$this->DKIM_QP($to_header));
    $subject  = str_replace('|','=7C',$this->DKIM_QP($subject_header)); // Copied header fields (dkim-quoted-printable
 
    $body     = $this->DKIM_BodyC($body);
		$DKIMlen  = strlen($body) ; // Length of body
    $DKIMb64  = base64_encode(pack('H*',sha1($body))); // Base64 of packed binary SHA-1 hash of body
    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
    $dkimhdrs = "DKIM-Signature: v=1; k=rsa; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
                "\th=mime-version:x-originating-ip:date:message-id:subject:from:to:content-type;\r\n".
                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
                "\tz=$from\r\n".
                "\t|$to\r\n".
                "\t|$subject;\r\n".
                "\tbh=" . $DKIMb64 . ";\r\n".
                "\tb=";
    $toSign   = $this->DKIM_HeaderC($mime_header . "\r\n" . $date_header . "\r\n" . $msgid_header . "\r\n" . $subject_header . "\r\n" . $from_header . "\r\n" . $to_header . "\r\n" . $content_header . " ". $boundary_header . "\r\n" .$dkimhdrs);
    $signed   = $this->DKIM_Sign($toSign);
    return "X-PHPMAILER-DKIM: phpmailer.worxware.com\n".$dkimhdrs.$signed."\r\n";
  }
Avalion est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 10/06/2011, 15h49   #4
Membre régulier
 
Homme
Étudiant
Inscription : juin 2011
Messages : 55
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : France, Val d'Oise (Île de France)

Informations professionnelles :
Activité : Étudiant
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : juin 2011
Messages : 55
Points : 77
Points : 77
Un nouveau problème se profile... Tout mes tests étaient plutôt simple... Mais voici que les accents dans le sujet font planter la signature... Or, selon une règle que j’essaie de déterminer, le contenu du sujet est encodé soit en ?iso-8859-1?B? soit en ?iso-8859-1?Q?...

Quelqu'un sait quelle est cette règle ? Ou alors quelle fonction utiliser pour transformer le sujet en ces encodage ?

Encore plus troublant :

L'encodage ?iso-8859-1?B? correspond au base64_encode, alors que le ?iso-8859-1?Q? est une mise en forme ASCII ('été' => '=E9t=E9').
La ou c'est troublant c'est qu'on penserait que ?iso-8859-1?B? s'applique donc pour des sujets plus compliqué que pour l'autre alors qu'en testant on obtient :
'méssè' =>?iso-8859-1?B?belzc+g=?=
'méssè et' =>?iso-8859-1?Q?m=E9ss=E8_et?=
Avalion est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 04/11/2011, 18h42   #5
Invité de passage
 
Inscription : avril 2003
Messages : 7
Détails du profil
Informations forums :
Inscription : avril 2003
Messages : 7
Points : 2
Points : 2
Bonjour,

Citation:
Envoyé par Avalion Voir le message
Bonjour à tous. J'ai fini par résoudre mon problème tout seul.

Je vous envoie donc mes fonctions PHPMailer associées au DKIM, pour que cela fonctionne (normalement) sans problèmes. (a remplacer directement dans PHPMailer !)
Je suis confronté au même problème, mais je suis confronté à un soucis de code ... puisqu'au moins la fonction sss_error_track n'est pas présente ...

mais peut-etre ne sert-elle a rien d'important ...

Cordialement,

Stéphane
Sbouli est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 20h34.


 
 
 
 
Partenaires

Hébergement Web