Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
Torrent Signing [BETA]
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / V4 / Support & Suggestions

2022-06-14 19:09:07
This is my attempt at creating a PHP-solution for BEP 35 - torrent signing using openssl extensions.

https://www.bittorrent.org/beps/bep_0035.html

Updated: June 20, 2022

<?
// BEP_35 - Torrent Signing
function signtorrent(string $in, string $out, string $certfile, string $keyfile): bool
{
  $parsed = Bencode::decode(file_get_contents($in), bigInt: BigInt::INTERNAL);
  if (!isset($array['signatures'])) {
      $certFile      = file_get_contents($certfile);
      $keyFile       = file_get_contents($keyfile);
      $result        = openssl_x509_parse($certFile);
      $keyPassphrase = 'password';
      $privatekey    = openssl_get_privatekey($keyFile, $keyPassphrase);
      openssl_sign($parse, $signature, $privatekey);
      $info       = array();
      $fields     = $result['issuer']['C'] . $result['issuer']['ST'] . $result['issuer']['L'] . $result['issuer']['O'] . $result['issuer']['OU'] . $result['validFrom'] . $result['validTo'] . $result['subject']['O'] . $result['subject']['CN'];
      $signatures = array(
          'signatures' => array(
              'com.bittorrent' => array(
                  'certificate' => $fields . $signature, // optional, DER encoded x.509 certificate
                  'info' => $info, // optional
                  'signature' => sha1(Bencode::encode($parsed['info'])) . (!empty($info) ? Bencode::encode($info) : '') // signed data = info + sig info if present
              )
          )
      );
      if (isset($array['url-list'])) {
          unset($array['url-list']);
      }
      $array = array_merge($parsed, $signatures);
      if (file_put_contents($out, Bencode::encode($array))) {
          return true;
      }
  }
  return false;
}
Last edited by STorrents2020 on 2022-06-20 05:53:49
2022-06-15 02:58:17

<?php

function reverseDNS(string $hostname) : ?string
{
   if (! preg_match('/^[a-z0-9][a-z0-9\.\-]*[.][a-z]{2,}$/', $hostname)) {
       return null;
   }
   $pieces = explode('.', $hostname);
   $pieces = array_reverse($pieces);
   return join('.', $pieces);
}

echo reverseDNS('bittorrent.com') . "\n";


They recommend to use reverse dns, this would return com.bittorrent, also as stated in the BEP

Quote:
signature - Required byte string. This is the RSA signature of the concatenation of the torrent's info dictionary and the signature's info dictionary (if present).
Last edited by mostvotedplayer on 2022-06-15 03:00:21
2022-06-15 05:26:45
Nice! Thank you, I missed that. Do you see any reason why the encoding would differ?
2022-06-15 06:37:27
As i said in the previous post this is wrong:


 'signature' => sha1($signature)


At minimum it should include the info dictionary.

 

$dict = []; // decoded .torrent
$dict['signatures']['com.bittorrent'] = [
   'signature' => sha1(Bencode($dict['info']))
];


The example provided shows


"com.bittorrent": {
           "certificate": optional, DER encoded x.509 certificate,
           "info": { ... } optional,
           "signature": signed data = info + sig info if present,
       }


if you add the info field then needs to be


$info = []; // It's a dictionary...
$dict = []; // decoded .torrent
$dict['signatures']['com.bittorrent'] = [
   'info'           => $info,
   'signature' => sha1(Bencode($dict['info']) . Bencode($info))
];
$dict = Bencode($dict); // Encode entire torrent.
2022-06-20 05:07:50
I have this so far, matching as close as possible to the format used in. Still not matching the encoded method the C++ implementation

https://github.com/bittorrent/ut-signing-tool/blob/master/src/main.cpp


<?
// BEP_35 - Torrent Signing
function signtorrent(string $in, string $out, string $certfile, string $keyfile): bool
{
   $parsed = Bencode::decode(file_get_contents($in), bigInt: BigInt::INTERNAL);
   if (!isset($array['signatures'])) {
       $certFile      = file_get_contents($certfile);
       $keyFile       = file_get_contents($keyfile);
       $result        = openssl_x509_parse($certFile);
       $keyPassphrase = 'password';
       $privatekey    = openssl_get_privatekey($keyFile, $keyPassphrase);
       openssl_sign($parse, $signature, $privatekey);
       $info       = array();
       $fields     = $result['issuer']['C'] . $result['issuer']['ST'] . $result['issuer']['L'] . $result['issuer']['O'] . $result['issuer']['OU'] . $result['validFrom'] . $result['validTo'] . $result['subject']['O'] . $result['subject']['CN'];
       $signatures = array(
           'signatures' => array(
               'com.bittorrent' => array(
                   'certificate' => $fields . $signature, // optional, DER encoded x.509 certificate
                   'info' => $info, // optional
                   'signature' => sha1(Bencode::encode($parsed['info'])) . (!empty($info) ? Bencode::encode($info) : '') // signed data = info + sig info if present
               )
           )
       );
       if (isset($array['url-list'])) {
           unset($array['url-list']);
       }
       $array = array_merge($parsed, $signatures);
       if (file_put_contents($out, Bencode::encode($array))) {
           return true;
       }
   }
   return false;
}


echo signtorrent('in.torrent', 'out.torrent', 'signing/certificate.pem', 'signing/private.key') ? 'success' : 'failed';
Last edited by STorrents2020 on 2022-06-20 05:51:52
2022-06-20 17:07:14
I did some testing on this earlier and seems my earlier assumptions was wrong.

The tool only generated two fields for me:

signatures.domain.certificate - See 1
signatures.domain.signature  - See 2

1.) This is a binary string:

The certificate file would be something like:

-----BEGIN CERTIFICATE-----
(Content Here is Base64 encoded)
-----END CERTIFICATE-----

DER format would be the base64_decoded data of the certificate (i think.)

2.) This is also a binary string:

I am guessing you need to use openssl_sign here.
2022-06-20 19:19:02
I was wondering about that after opening my .pem cert and viewing the encoding. The logic appears to be as much as I can assume is what is needed.

Mimicking the cpp script is hard but I think it’s correct, only I replaced fopen seek with file_get_contents, the second being more memory efficient.

If we can hammer this out with basic testing, we have a universal BEP for anyone
2022-06-20 20:35:32

<?php

/**
* Convert PEM to DER.
*
* @param  string   $buffer The contents of the PEM.
* @return stdClass
*/
function convertToDer(string $buffer) : stdClass
{
   $result = new stdClass();
   if (preg_match('/^[-]{5}BEGIN CERTIFICATE[-]{5}([\S\s]+)[-]{5}END CERTIFICATE[-]{5}$/', $buffer, $m)) {
       $result->status = 'success';
       $result->result = base64_decode($m[1]);
   } else {
       $result->status = 'failure';
   }
   return $result;
}

$buffer  = file_get_contents('example.crt');
$convert = convertToDer($buffer);
if ($convert->status === 'success') {
   $dict['signatures']['link.m2g'] = [
       'certificate' => $convert->result,
       'signature'   => ''
   ];
} else {
   print("Something went wrong.\n");
}


To generate the signature you need to Bencode the info dictionary and then pass that to openssl_sign the raw output is the answer.
2022-06-20 20:55:59
A finished result would look something like:


<?php

// Load Libs.
include('/var/www/html/1xbtc/System/Library/BitTorrent/Bencoder.php');
include('/var/www/html/1xbtc/System/Library/BitTorrent/Bdecoder.php');

$bencoder = new \System\Library\BitTorrent\Bencoder();
$bdecoder = new \System\Library\BitTorrent\Bdecoder();

// Parse torrent.
$torrent  = file_get_contents('test.torrent');
$decoded  = $bdecoder->decode($torrent);

// Bencode info dictionary.
$infoField = $bencoder->encode($decoded[1]['info']);


/**
* Convert PEM to DER.
*
* @param  string   $buffer The contents of the PEM.
* @return stdClass
*/
function convertToDer(string $buffer) : stdClass
{
   $result = new stdClass();
   if (preg_match('/^[-]{5}BEGIN CERTIFICATE[-]{5}([\S\s]+)[-]{5}END CERTIFICATE[-]{5}$/', $buffer, $m)) {
       $result->status = 'success';
       $result->result = base64_decode($m[1]);
   } else {
       $result->status = 'failure';
   }
   return $result;
}

// Verify private key.
$pKey = file_get_contents('server.key');
$pKey = openssl_pkey_get_private($pKey, 'howarth');

// Sign info.
openssl_sign($infoField, $signature, $pKey);

$buffer  = file_get_contents('server.crt');
$convert = convertToDer($buffer);
if ($convert->status === 'success') {
   $dict = $decoded[1];
   $dict['signatures']['link.m2g'] = [ // link.m2g would be Common Name in reverse DNS notation.
       'certificate' => $convert->result,
       'signature'   => $signature
   ];
   $dict = $bencoder->encode($dict);
   file_put_contents('output.torrent', $dict);
} else {
   print("Something went wrong.\n");
}
Last edited by mostvotedplayer on 2022-06-20 21:26:22
2022-06-21 08:11:06
Updated to match tool output


function sign_torrent(string $name, int $torrent_id, $bencoded): bool
{
   global $db;

   $report = array();
   if (file_put_contents('unsigned.torrent', $bencoded)) {
       $decoded = Bencode::decode($bencoded, bigInt: BigInt::INTERNAL);
       if (!is_null($decoded)) {
           $report[] = 'Torrent loaded.';
       }
       $pKey = file_get_contents('private.key');
       $pKey = openssl_pkey_get_private($pKey, 'password');
       if ($pKey) {
           $report[] = 'Private key loaded.';
       }
       openssl_sign(Bencode::encode($decoded['info']), $signature, $pKey);
       $buffer = file_get_contents('certificate.pem');
       $field  = openssl_x509_parse($buffer);
       if ($buffer) {
           $report[] = sprintf('Certificate loaded. (indentity = %s)', $field['subject']['CN']);
       }
       $convert = convertToDer($buffer);
       if ($convert->status === 'success') {
           $dict = $decoded;
           $dict      = array(
               'signatures' => array(
                   'com.switch-torrents' => array(
                       'certificate' => $convert->result,
                       'signature' => $signature
                   )
               )
           );
           $report[] = sprintf('Signature size: %s', intval(mb_strlen($signature, '8bit')));
           $report[] = sprintf('Bencoded certificate size: %s', intval(mb_strlen(Bencode::encode($convert->result), '8bit')));
           $report[] = sprintf('Bencoded signature size: %s', intval(mb_strlen(Bencode::encode($signature), '8bit')));
           $dict     = Bencode::encode($decoded + $dict);
           if (file_put_contents('signed.torrent', $dict)) {
               $report[] = 'Done!';
               $db->query_params('INSERT INTO signing_log (added, txt) VALUES(NOW(), :log)', array(
                   'log' => sprintf("Torrent \"%s\" ID: %s %s  %s  %s  %s  %s  %s  %s", $name, $torrent_id, $report[0], $report[1], $report[2], $report[3], $report[4], $report[5], $report[6])
               ));
               return true;
           }
       } else {
           return false;
       }
   } else {
       return false;
   }
}
2022-06-21 19:28:33
I think it’s better to return the bencoded data and only return bool on error. That way I’m not using file_get_contents on download.php to read signed.torrent
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 2
  • Members: 0
  • Guests online: 2
  • Comments: 3
  • Messages: 1,728