]> WPIA git - cassiopeia.git/blobdiff - src/simpleOpensslSigner.cpp
add: Basic implementation to generate the certificate serial
[cassiopeia.git] / src / simpleOpensslSigner.cpp
index 3a22a7cdf371539bd8ca2423b9c1a22bc3ef62f5..c8d0bdf7a5cbaaa6d52ec4fa5f89c410bbf4cf0e 100644 (file)
@@ -1,6 +1,7 @@
 #include "simpleOpensslSigner.h"
 
 #include <iostream>
+#include <fstream>
 
 #include <openssl/ssl.h>
 #include <openssl/err.h>
@@ -9,6 +10,8 @@
 #include <openssl/engine.h>
 #include <openssl/x509v3.h>
 
+#include "X509.h"
+
 extern std::vector<Profile> profiles;
 
 std::shared_ptr<int> SimpleOpensslSigner::lib_ref(
@@ -67,7 +70,50 @@ SimpleOpensslSigner::SimpleOpensslSigner() {
     caKey = loadPkeyFromFile( profiles[0].key );
 }
 
-int serial = 10;
+SimpleOpensslSigner::~SimpleOpensslSigner() {
+}
+
+std::shared_ptr<BIGNUM> SimpleOpensslSigner::nextSerial() {
+    std::ifstream serialif( "serial" );
+    std::string res;
+    serialif >> res;
+    serialif.close();
+
+    BIGNUM* bn = 0;
+
+    if( res == "" ) {
+        bn = BN_new();
+
+        if( !bn ) {
+            throw "Initing serial failed";
+        }
+    } else {
+        if( !BN_hex2bn( &bn, res.c_str() + 1 ) ) {
+            throw "Parsing serial failed.";
+        }
+    }
+
+    std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
+
+    std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char* ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
+    int len = BN_bn2bin( serial.get(), data.get() );
+    data.get()[len] = 0x0;
+    data.get()[len + 1] = 0x0; // profile id
+    data.get()[len + 2] = 0x0;
+    data.get()[len + 3] = 0x0; // signer id
+
+    if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
+        throw "Big number math failed while calcing serials.";
+    }
+
+    char* serStr = BN_bn2hex( serial.get() );
+    std::ofstream serialf( "serial" );
+    serialf << serStr;
+    serialf.close();
+    OPENSSL_free( serStr );
+
+    return std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16 , 0 ), BN_free );
+}
 
 std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TBSCertificate> cert ) {
     if( !caKey ) {
@@ -105,7 +151,8 @@ std::shared_ptr<SignedCertificate> SimpleOpensslSigner::sign( std::shared_ptr<TB
 
     c.setIssuerNameFrom( caCert );
     c.setPubkeyFrom( req );
-    c.setSerialNumber( serial++ );
+    std::shared_ptr<BIGNUM> ser = nextSerial();
+    c.setSerialNumber( ser.get() );
     c.setTimes( 0, 60 * 60 * 24 * 10 );
     c.setExtensions( caCert, cert->SANs );