Example #1
0
RSA* LoadPublicKey(const char* filename)
{
    unsigned long err;
    FILE* fp;
    RSA* key;
    static char *passphrase = "Cfengine passphrase";

    fp = fopen(filename, "r");
    if (fp == NULL)
    {
        Log(LOG_LEVEL_ERR, "Cannot open file '%s'. (fopen: %s)", filename, GetErrorStr());
        return NULL;
    };

    if ((key = PEM_read_RSAPublicKey(fp, NULL, NULL, passphrase)) == NULL)
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Error reading public key. (PEM_read_RSAPublicKey: %s)",
            ERR_reason_error_string(err));
        fclose(fp);
        return NULL;
    };

    fclose(fp);

    if (BN_num_bits(key->e) < 2 || !BN_is_odd(key->e))
    {
        Log(LOG_LEVEL_ERR, "RSA Exponent in key '%s' too small or not odd. (BN_num_bits: %s)",
            filename, GetErrorStr());
        return NULL;
    };

    return key;
}
Example #2
0
void test_RSA_encryption(){
	unsigned char message[129];
  	strncpy((char*)message,"Hello. This is Timothy.",sizeof(message));
	unsigned char ciphertext[129];
	unsigned char decrypted[129];
	memset(ciphertext,'\0',129);
	memset(decrypted,'\0',129);
	FILE* fp=fopen("publickey.pem","r");
	RSA* pubkey=NULL;
	RSA* privkey=NULL;
	
	//Get public key
	if((pubkey=PEM_read_RSAPublicKey(fp,&pubkey,NULL,NULL))==NULL){
		printf("Error reading public key from file\n");
		return;
	}
	fclose(fp);
	printf("Original message: %s\n",message);	
	int encrypt_len=encrypt_with_public_key(pubkey,message,ciphertext,23);
	printf("Encrypted message: %s\n",ciphertext);
	privkey=get_private_key();
	fp=fopen("privatekeyTEST.pem","w+");
		
	int success=PEM_write_RSAPrivateKey(fp,privkey,NULL,NULL,0,NULL,NULL);
	fclose(fp);
	if(success!=1){
		perror("Issue writing the private key to file: ");
	}
	decrypt_with_private_key(privkey,ciphertext,decrypted,encrypt_len);
	printf("Decrypted message: %s\n",decrypted);
	RSA_free(pubkey);
	RSA_free(privkey);
}
Example #3
0
Key::Key(string publicKeyFile, string privateKeyFile)
{
    rsa = NULL;
    privateKey = NULL;
    publicKey = NULL;
    priName = privateKeyFile;
    pubName = publicKeyFile;
    
    if (!privateKeyFile.empty()) {
        FILE *fp = fopen(privateKeyFile.c_str(), "r");
        if (fp == NULL) {
            cout << "Private Key File Error!" << endl;
            return ;
        }
        privateKey = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
        fclose(fp);
    }
    if (!publicKeyFile.empty()) {
        FILE *fp = fopen(publicKeyFile.c_str(), "r");
        if (fp == NULL) {
            cout << "Public Key File Error!" << endl;
            return ;
        }
//        rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
        publicKey = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
        fclose(fp);
        return ;
    }
    cout << "Error Open Private Key or Public Key!" << endl;
}
Example #4
0
//使用公钥加密
int rsa_encrypt(char *in, const char *key_path, char* out)
{
    RSA *p_rsa;
    FILE *file;
    int rsa_len;
    if ((file=fopen(key_path, "r"))==NULL)
    {
        perror("open key file error");
        return 0;
    }

    //if ((p_rsa=PEM_read_RSA_PUBKEY(file, NULL, &ccbb, NULL))==NULL){
    if ((p_rsa=PEM_read_RSAPublicKey(file, NULL, NULL, NULL))==NULL){
        ERR_print_errors_fp(stdout);
        return 0;
    }
    rsa_len=RSA_size(p_rsa);
    if (RSA_public_encrypt(rsa_len, (unsigned char*)in, (unsigned char*)out, p_rsa, RSA_NO_PADDING)<0)
    {
        return 0;
    }
    RSA_free(p_rsa);
    fclose(file);
    return 1;
}
Example #5
0
/***************************************************************************** 
    Function      : Verify Digital Signature(RSA) <Binary>
    Return        : int
	************************************************ Yuji Yamawaki 02.02.07 *****/
int
openSOAPSecVerifyRSASignBin
(int                  iType,          /* (i)  Hash Type(OPENSOAP_HA_*) */
 unsigned char*       szIn,           /* (i)  Signature */
 unsigned long        ulInSize,       /* (i)  Signature Size */
 const unsigned char* szData,         /* (i)  Original Data */
 unsigned long        ulDataSize,     /* (i)  Original Data Size */
 FILE*                fpPubKey)       /* (i)  RSA Public Key File Stream */
{
    RSA*  pRsa = NULL;
    unsigned char* szHash = NULL;
    unsigned long  ulLenHash;
    int            nRet = OPENSOAP_NO_ERROR;
    int            iRes;
    fpos_t         fposKey;
    /* Check Arguments */
    if (szIn == NULL || ulInSize == 0 || szData == NULL || ulDataSize == 0 ||
        fpPubKey == NULL) {
        return OPENSOAP_PARAMETER_BADVALUE;
    }
    /* Backup Stream's Position */
    if (fgetpos(fpPubKey, &fposKey) != 0) {
        nRet = OPENSOAP_IO_READ_ERROR;
        goto FuncEnd;
    }
    /* Hash Original Data */
    nRet = openSOAPSecMakeHash(iType, szData, ulDataSize,
                               &ulLenHash, &szHash);
    if (OPENSOAP_FAILED(nRet)) {
        goto FuncEnd;
    }
    /* Generate RSA from Public key */
    if (PEM_read_RSAPublicKey(fpPubKey, &pRsa, NULL, NULL) == NULL) {
        nRet = OPENSOAP_SEC_SIGNVERIFY_ERROR;
        goto FuncEnd;
    }
    /* Recover File Position */
    if (fsetpos(fpPubKey, &fposKey) != 0) {
        nRet = OPENSOAP_IO_READ_ERROR;
        goto FuncEnd;
    }
    /* Verify Signature */
    iRes = RSA_verify(convType(iType),
                      szHash,
                      ulLenHash,
                      szIn,
                      (int)ulInSize,
                      pRsa);
    if (iRes != 1) {
        nRet = OPENSOAP_SEC_SIGNVERIFY_ERROR;
    }
 FuncEnd:
    if (szHash != NULL)
        free(szHash);
    /* Terminate */
    RSA_free(pRsa);
    return nRet;
}
Example #6
0
void *readpubkey(char *pubfile) {
	FILE *fp;
	RSA *key=NULL;
	static char *passphrase = "Cfengine passphrase";

	if((fp = fopen(pubfile, "r")) == NULL) {
		fprintf(stderr,"Error: Cannot locate Public Key file '%s'.\n", pubfile);
		return NULL;
	}
	if((key = PEM_read_RSAPublicKey(fp,(RSA **)NULL,NULL,passphrase)) == NULL) {
		fprintf(stderr,"Error: failed reading Public Key in '%s' file.\n", pubfile);
		return NULL;
	}
	fclose(fp);
	return (void *)key;
}
Example #7
0
RSA *LoadPublic(char *file) {
    RSA *pubkey = NULL;
    FILE *fd = NULL;
    int ret = 0;
    
    if ((fd = fopen(file, "r")) == NULL) return NULL;
    
    pubkey = PEM_read_RSAPublicKey(fd, NULL, NULL, NULL);
    
    if (pubkey == NULL) {
        ERR_print_errors_fp(stderr);
    }
    
    fclose(fd);
    
    return pubkey;
}
Example #8
0
int COsslKey::LoadPublicKey( const sqbind::stdString &sFile )
{_STT();

	Destroy();

	m_pkey = EVP_PKEY_new();
	if ( !m_pkey )
	{	oexERROR( 0, oexT( "EVP_PKEY_new() failed" ) );
		Destroy();
		return 0;
	} // end if

	oex::CStr8 name = oexStrToMb( oex::CStr( sFile.c_str(), sFile.length() ) );

	FILE *fp = fopen( name.Ptr(), "r" );
	if ( !fp )
	{	oexERROR( oexGetLastError(), oexMks( oexT( "fopen( '" ), oexMbToStr( name ), oexT( "' ) failed" ) ) );
		Destroy();
		return 0;
	} // end if

	RSA *rsa = PEM_read_RSAPublicKey( fp, oexNULL, oexNULL, (void*)getPasswordPtr() );
	if ( !rsa )
		rsa = PEM_read_RSA_PUBKEY( fp, oexNULL, oexNULL, (void*)getPasswordPtr() );
	if ( !rsa )
	{	oexERROR( 0, oexT( "PEM_read_RSAPublicKey() failed" ) );
		fclose( fp );
		Destroy();
		return 0;
	} // end if

	fclose( fp );

	// Assign key
	if ( !EVP_PKEY_assign_RSA( m_pkey, rsa ) )
	{	oexERROR( 0, oexT( "EVP_PKEY_assign_RSA() failed" ) );
		Destroy();
		return 0;
	} // end if
	rsa = oexNULL;

	return 1;
}
Example #9
0
        RSAKey RSAKey::createFromPEMPublicKeyFile(const std::string& filename, PEMPassphraseCallback callback, void* userdata)
        {
            FILE* fp = fopen(filename.c_str(), "r");

            if (fp == NULL)
            {
                THROW_EXCEPTION_WITH_LOG(Exception::exception, "Cannot open the file.");
            }

            RSA* prsa = PEM_read_RSAPublicKey(fp, NULL, callback, userdata);

            fclose(fp);

            EXCEPTION_ASSERT_WITH_LOG(prsa, OpenSSLException, "Unable to parse the RSA public key PEM file");

            std::shared_ptr<RSA> sprsa(prsa, RSA_free);

            return RSAKey(sprsa, false);
        }
Example #10
0
void Key::reload()
{
    if (!priName.empty()) {
        FILE *fp = fopen(priName.c_str(), "r");
        if (fp == NULL) {
            cout << "Private Key File Error!" << endl;
            return ;
        }
        privateKey = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
        fclose(fp);
    }
    if (!pubName.empty()) {
        FILE *fp = fopen(pubName.c_str(), "r");
        if (fp == NULL) {
            cout << "Public Key File Error!" << endl;
            return ;
        }
        publicKey = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
        fclose(fp);
        return ;
    }
}
Example #11
0
int
openssl_read_pem_pubkey(const char *f, __ops_pubkey_t *key, const char *type, int verbose)
{
    FILE	*fp;
    DSA	*dsa;
    RSA	*rsa;
    int	 ok;
    
    OpenSSL_add_all_algorithms();
    if ((fp = fopen(f, "r")) == NULL) {
        if (verbose) {
            (void) fprintf(stderr, "can't open '%s'\n", f);
        }
        return 0;
    }
    ok = 1;
    if (strcmp(type, "ssh-rsa") == 0)
    {
        rsa = PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);

        if(!rsa)
            rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
        
        key->key.rsa.e = rsa->e;
        key->key.rsa.n = rsa->n;
    }
    else if (strcmp(type, "ssh-dss") == 0) {
        if ((dsa = PEM_read_DSA_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
            ok = 0;
        } else {
            key->key.dsa.y = dsa->pub_key;
        }
    } else {
        ok = 0;
    }
    (void) fclose(fp);
    return ok;
}
Example #12
0
Certificate *Certificate::create(const string subject, const string issuer, const string validity, const Node::Id_t owner, const string pubKeyFile)
{
	FILE *f = fopen(pubKeyFile.c_str(), "r");

	if (!f) {
		HAGGLE_ERR("Could not open public key file %s\n", pubKeyFile.c_str());
		return NULL;
	}

	RSA *pubKey = PEM_read_RSAPublicKey(f, NULL, NULL, NULL);

	fclose(f);

	if (!pubKey) {
		HAGGLE_ERR("Could not read RSA public key\n");
		return NULL;
	}

	Certificate *c = new Certificate(subject, issuer, validity, owner, pubKey);
	
	RSA_free(pubKey);
        
	return c;
}
Example #13
0
/**
 * @return true the error is not so severe that we must stop
 */
bool LoadSecretKeys(const char *policy_server)
{
    static char *passphrase = "Cfengine passphrase";

    {
        FILE *fp = fopen(PrivateKeyFile(GetWorkDir()), "r");
        if (!fp)
        {
            Log(LOG_LEVEL_INFO, "Couldn't find a private key at '%s', use cf-key to get one. (fopen: %s)", PrivateKeyFile(GetWorkDir()), GetErrorStr());
            return true;
        }

        if ((PRIVKEY = PEM_read_RSAPrivateKey(fp, (RSA **) NULL, NULL, passphrase)) == NULL)
        {
            unsigned long err = ERR_get_error();
            Log(LOG_LEVEL_ERR, "Error reading private key. (PEM_read_RSAPrivateKey: %s)", ERR_reason_error_string(err));
            PRIVKEY = NULL;
            fclose(fp);
            return true;
        }

        fclose(fp);
        Log(LOG_LEVEL_VERBOSE, "Loaded private key at '%s'", PrivateKeyFile(GetWorkDir()));
    }

    {
        FILE *fp = fopen(PublicKeyFile(GetWorkDir()), "r");
        if (!fp)
        {
            Log(LOG_LEVEL_ERR, "Couldn't find a public key at '%s', use cf-key to get one (fopen: %s)", PublicKeyFile(GetWorkDir()), GetErrorStr());
            return true;
        }

        if ((PUBKEY = PEM_read_RSAPublicKey(fp, NULL, NULL, passphrase)) == NULL)
        {
            unsigned long err = ERR_get_error();
            Log(LOG_LEVEL_ERR, "Error reading public key at '%s'. (PEM_read_RSAPublicKey: %s)", PublicKeyFile(GetWorkDir()), ERR_reason_error_string(err));
            PUBKEY = NULL;
            fclose(fp);
            return true;
        }

        Log(LOG_LEVEL_VERBOSE, "Loaded public key '%s'", PublicKeyFile(GetWorkDir()));
        fclose(fp);
    }

    if ((BN_num_bits(PUBKEY->e) < 2) || (!BN_is_odd(PUBKEY->e)))
    {
        Log(LOG_LEVEL_ERR, "The public key RSA exponent is too small or not odd");
        return false;
    }

    if (GetAmPolicyHub(CFWORKDIR))
    {
        unsigned char digest[EVP_MAX_MD_SIZE + 1];

        char dst_public_key_filename[CF_BUFSIZE] = "";
        {
            char buffer[EVP_MAX_MD_SIZE * 4];
            HashPubKey(PUBKEY, digest, CF_DEFAULT_DIGEST);
            snprintf(dst_public_key_filename, CF_MAXVARSIZE, "%s/ppkeys/%s-%s.pub", CFWORKDIR, "root", HashPrintSafe(CF_DEFAULT_DIGEST, digest, buffer));
            MapName(dst_public_key_filename);
        }

        struct stat sb;
        if ((stat(dst_public_key_filename, &sb) == -1))
        {
            char src_public_key_filename[CF_BUFSIZE] = "";
            snprintf(src_public_key_filename, CF_MAXVARSIZE, "%s/ppkeys/localhost.pub", CFWORKDIR);
            MapName(src_public_key_filename);

            // copy localhost.pub to root-HASH.pub on policy server
            if (!LinkOrCopy(src_public_key_filename, dst_public_key_filename, false))
            {
                Log(LOG_LEVEL_ERR, "Unable to copy policy server's own public key from '%s' to '%s'", src_public_key_filename, dst_public_key_filename);
            }

            if (policy_server)
            {
                LastSaw(policy_server, digest, LAST_SEEN_ROLE_CONNECT);
            }
        }
    }

    return true;
}
Example #14
0
static void test_TLSVerifyPeer(void)
{
    ASSERT_IF_NOT_INITIALIZED;
    RESET_STATUS;

    SSL *ssl = NULL;
    ConnectionInfo *conn_info = NULL;

    /*
     * Open a socket and establish a tcp connection.
     */
    struct sockaddr_in server_addr;
    int server = 0;
    int result = 0;

    conn_info = ConnectionInfoNew();

    memset(&server_addr, 0, sizeof(struct sockaddr_in));
    server = socket(AF_INET, SOCK_STREAM, 0);
    assert_int_not_equal(-1, server);
    server_addr.sin_family = AF_INET;
    ConnectionInfoSetSocket(conn_info, server);
    /* We should not use inet_addr, but it is easier for this particular case. */
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(8035);
    /*
     * Connect
     */
    result = connect(server, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
    assert_int_not_equal(-1, result);
    /*
     * Create a SSL instance
     */
    ssl = SSL_new(SSLCLIENTCONTEXT);
    assert_true(ssl != NULL);
    SSL_set_fd(ssl, server);
    /*
     * Establish the TLS connection over the socket.
     */
    result = SSL_connect(ssl);
    assert_int_not_equal(-1, result);
    /*
     * Fill the remaining fields on ConnectionInfo
     */
    ConnectionInfoSetProtocolVersion(conn_info, CF_PROTOCOL_TLS);
    ConnectionInfoSetSSL(conn_info, ssl);
    /*
     * Fill in the structures we need for testing.
     */
    X509 *certificate = NULL;
    FILE *certificate_stream = fopen(server_certificate_template_public, "r");
    certificate = PEM_read_X509(certificate_stream, (X509 **)NULL, NULL, NULL);
    assert_true(certificate != NULL);

    /*
     * Start testing
     */
    USE_MOCK(SSL_get_peer_certificate);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);

    USE_MOCK(X509_get_pubkey);
    X509_GET_PUBKEY_RETURN(NULL);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));

    /*
     * Due to the cleaning up we do after failing, we need to re read the certificate after
     * very failure. The same is true for the public key.
     */
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    EVP_PKEY *server_pubkey = NULL;
    FILE *stream = NULL;
    stream = fopen(server_name_template_public, "r");
    RSA *pubkey = PEM_read_RSAPublicKey(stream, (RSA **)NULL, NULL, NULL);
    server_pubkey = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(server_pubkey, pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);

    USE_MOCK(EVP_PKEY_type);
    EVP_PKEY_TYPE_RETURN(EVP_PKEY_DSA);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    EVP_PKEY_TYPE_RETURN(EVP_PKEY_RSA);

    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    USE_MOCK(X509_verify);
    X509_VERIFY_RETURN(-1);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    X509_VERIFY_RETURN(0);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    X509_VERIFY_RETURN(1);

    USE_MOCK(HavePublicKey);
    HAVEPUBLICKEY_RETURN(NULL);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    assert_int_equal(0, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));

    USE_MOCK(EVP_PKEY_cmp);
    EVP_PKEY_CMP_RETURN(-1);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    HAVEPUBLICKEY_RETURN(pubkey);
    assert_int_equal(0, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    EVP_PKEY_CMP_RETURN(0);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    HAVEPUBLICKEY_RETURN(pubkey);
    assert_int_equal(0, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    EVP_PKEY_CMP_RETURN(-2);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    HAVEPUBLICKEY_RETURN(pubkey);
    assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
    EVP_PKEY_CMP_RETURN(1);
    REREAD_CERTIFICATE(certificate_stream, certificate);
    SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
    REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
    X509_GET_PUBKEY_RETURN(server_pubkey);
    HAVEPUBLICKEY_RETURN(pubkey);
    assert_int_equal(1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));

    /*
     * Shutting down is not as easy as it seems.
     */
    do {
        result = SSL_shutdown(ssl);
        assert_int_not_equal(-1, result);
    } while (result != 1);
    ConnectionInfoDestroy(&conn_info);
    RESET_STATUS;
}
Example #15
0
void ssl_client_init()
{
    /*
     * This is twisted. We can generate the required keys by calling RSA_generate_key,
     * however we cannot put the private part and the public part in the two containers.
     * For that we need to save each part to a file and then load each part from
     * the respective file.
     */
    RSA *key = NULL;
    key = RSA_generate_key(1024, 17, NULL, NULL);
    if (!key)
    {
        correctly_initialized = false;
        return;
    }
    char name_template_private[] = "/tmp/tls_test/mnopqrXXXXXX";
    char name_template_public[] = "/tmp/tls_test/stuvwxXXXXXX";
    int private_key_file = 0;
    FILE *private_key_stream = NULL;
    int ret = 0;

    private_key_file = mkstemp(name_template_private);
    if (private_key_file < 0)
    {
        correctly_initialized = false;
        return;
    }
    private_key_stream = fdopen(private_key_file, "w+");
    if (!private_key_stream)
    {
        correctly_initialized = false;
        return;
    }
    ret = PEM_write_RSAPrivateKey(private_key_stream, key, NULL, NULL, 0, 0, NULL);
    if (ret == 0)
    {
        correctly_initialized = false;
        return;
    }
    fseek(private_key_stream, 0L, SEEK_SET);
    PRIVKEY = PEM_read_RSAPrivateKey(private_key_stream, (RSA **)NULL, NULL, NULL);
    if (!PRIVKEY)
    {
        correctly_initialized = false;
        return;
    }
    fclose(private_key_stream);

    int public_key_file = 0;
    FILE *public_key_stream = NULL;
    public_key_file = mkstemp(name_template_public);
    if (public_key_file < 0)
    {
        correctly_initialized = false;
        return;
    }
    public_key_stream = fdopen(public_key_file, "w+");
    if (!public_key_stream)
    {
        correctly_initialized = false;
        return;
    }
    ret = PEM_write_RSAPublicKey(public_key_stream, key);
    if (ret == 0)
    {
        correctly_initialized = false;
        return;
    }
    fseek(public_key_stream, 0L, SEEK_SET);
    PUBKEY = PEM_read_RSAPublicKey(public_key_stream, (RSA **)NULL, NULL, NULL);
    if (!PUBKEY)
    {
        correctly_initialized = false;
        return;
    }
    fclose(public_key_stream);
    RSA_free(key);

    SSLCLIENTCONTEXT = SSL_CTX_new(SSLv23_client_method());
    if (SSLCLIENTCONTEXT == NULL)
    {
        Log(LOG_LEVEL_ERR, "SSL_CTX_new: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err1;
    }

    /* Use only TLS v1 or later.
       TODO option for SSL_OP_NO_TLSv{1,1_1} */
    SSL_CTX_set_options(SSLCLIENTCONTEXT,
                        SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

    /* Never bother with retransmissions, SSL_write() should
     * always either write the whole amount or fail. */
    SSL_CTX_set_mode(SSLCLIENTCONTEXT, SSL_MODE_AUTO_RETRY);

    /*
     * Create cert into memory and load it into SSL context.
     */

    if (PRIVKEY == NULL || PUBKEY == NULL)
    {
        correctly_initialized = false;
        return;
    }

    /* Generate self-signed cert valid from now to 50 years later. */
    {
        X509 *x509 = X509_new();
        X509_gmtime_adj(X509_get_notBefore(x509), 0);
        X509_time_adj(X509_get_notAfter(x509), 60*60*24*365*50, NULL);
        EVP_PKEY *pkey = EVP_PKEY_new();
        EVP_PKEY_set1_RSA(pkey, PRIVKEY);
        X509_NAME *name = X509_get_subject_name(x509);
        X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
                                   (const char *) "",
                                   -1, -1, 0);
        X509_set_issuer_name(x509, name);
        X509_set_pubkey(x509, pkey);

        const EVP_MD *md = EVP_get_digestbyname("sha384");
        if (md == NULL)
        {
            correctly_initialized = false;
            return;
        }
        ret = X509_sign(x509, pkey, md);

        EVP_PKEY_free(pkey);
        SSLCLIENTCERT = x509;

        if (ret <= 0)
        {
            Log(LOG_LEVEL_ERR,
                "Couldn't sign the public key for the TLS handshake: %s",
                ERR_reason_error_string(ERR_get_error()));
            goto err3;
        }
    }
    /* Log(LOG_LEVEL_ERR, "generate cert from priv key: %s", */
    /*     ERR_reason_error_string(ERR_get_error())); */

    SSL_CTX_use_certificate(SSLCLIENTCONTEXT, SSLCLIENTCERT);

    ret = SSL_CTX_use_RSAPrivateKey(SSLCLIENTCONTEXT, PRIVKEY);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Failed to use RSA private key: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    /* Verify cert consistency. */
    ret = SSL_CTX_check_private_key(SSLCLIENTCONTEXT);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Inconsistent key and TLS cert: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    /* Set options to always request a certificate from the peer, either we
     * are client or server. */
    SSL_CTX_set_verify(SSLCLIENTCONTEXT, SSL_VERIFY_PEER, NULL);
    /* Always accept that certificate, we do proper checking after TLS
     * connection is established since OpenSSL can't pass a connection
     * specific pointer to the callback (so we would have to lock).  */
    SSL_CTX_set_cert_verify_callback(SSLCLIENTCONTEXT, TLSVerifyCallback, NULL);

    correctly_initialized = true;
    return;

  err3:
    X509_free(SSLCLIENTCERT);
    SSLCLIENTCERT = NULL;
    SSL_CTX_free(SSLCLIENTCONTEXT);
    SSLCLIENTCONTEXT = NULL;
  err1:
    correctly_initialized = false;
    return;
}
Example #16
0
int main(int argc, char *argv[]) 
{ 
	if(argc != 2) {
		printf("usage: AT_file\n");
		exit(0);
	}
        char message[64]; 
    FILE* atfile = fopen(argv[1], "rb");
    fseek(atfile, 0L, SEEK_END);
    int fsize = ftell(atfile);
    //set back to normal
    fseek(atfile, 0L, SEEK_SET);
    fread(message,sizeof(char),fsize, atfile);
	fclose(atfile);

        unsigned char* signature; 
        unsigned int slen; 
        unsigned int verified; 

    	FILE* pri = fopen("private.pem", "rb");
    	FILE* pub = fopen("public.pem", "rb");

        RSA *private_key; 
        RSA *public_key; 

///////////////////////////////////////////////////// 

   private_key = PEM_read_RSAPrivateKey(pri, NULL, NULL, NULL); 
   if(private_key == NULL) { 
      ERR_print_errors_fp(stdout); 
   } 
 	
	char timestamp[20];
	sprintf(timestamp, "%d", (int)time(NULL));
	printf("%s\n", timestamp); 
	strcat(message, timestamp);

        signature = (unsigned char*) malloc(RSA_size(private_key)); 
        if(RSA_sign(NID_sha1, (unsigned char*) message, strlen(message), 
signature, &slen, private_key) != 1) { 
                ERR_print_errors_fp(stdout); 
        } 

	char timefilename[128];
	strncpy(timefilename, argv[1], 127);
	strcat(timefilename, ".timestamp");
	FILE* timefile = fopen(timefilename, "w");
	fwrite(timestamp,sizeof(char),strlen(timestamp),timefile);
	fclose(timefile);
	char signfilename[128];
	strncpy(signfilename, argv[1], 127);
	strcat(signfilename, ".signed");
	FILE* signfile = fopen(signfilename, "w");
	fwrite(signature,sizeof(char),slen,signfile);
	fclose(signfile);

////////////////////////////////////////////////// 

        unsigned char signedinput[1024]; 
	unsigned char* signedoutput;
    FILE* signedfile = fopen(signfilename, "r");
    fseek(signedfile, 0L, SEEK_END);
    int fsize2 = ftell(signedfile);
    //set back to normal
    fseek(signedfile, 0L, SEEK_SET);
    fread(signedinput,sizeof(char),fsize2, signedfile);
	fclose(signedfile);

        public_key = PEM_read_RSAPublicKey(pub, NULL, NULL, NULL); 
   if(public_key == NULL) { 
      ERR_print_errors_fp(stdout); 
   } 
        verified = RSA_verify(NID_sha1, (unsigned char*) message, 
strlen(message), signedinput, 256, public_key); 

///////////////////////////////////////////////////// 

        printf("VERIFIED: %d\n",verified); 

        RSA_free(private_key); 

        RSA_free(public_key); 

        return 0; 
} 
Example #17
0
RSA *HavePublicKey(char *username, char *ipaddress, char *digest)
{
    char keyname[CF_MAXVARSIZE], newname[CF_BUFSIZE], oldname[CF_BUFSIZE];
    struct stat statbuf;
    static char *passphrase = "public";
    unsigned long err;
    FILE *fp;
    RSA *newkey = NULL;

    snprintf(keyname, CF_MAXVARSIZE, "%s-%s", username, digest);

    CfDebug("HavePublickey(%s)\n", keyname);

    snprintf(newname, CF_BUFSIZE, "%s/ppkeys/%s.pub", CFWORKDIR, keyname);
    MapName(newname);

    if (cfstat(newname, &statbuf) == -1)
    {
        CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Did not find new key format %s", newname);
        snprintf(oldname, CF_BUFSIZE, "%s/ppkeys/%s-%s.pub", CFWORKDIR, username, ipaddress);
        MapName(oldname);

        CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Trying old style %s", oldname);

        if (cfstat(oldname, &statbuf) == -1)
        {
            CfDebug("Did not have old-style key %s\n", oldname);
            return NULL;
        }

        if (strlen(digest) > 0)
        {
            CfOut(OUTPUT_LEVEL_INFORM, "", " -> Renaming old key from %s to %s", oldname, newname);

            if (rename(oldname, newname) != 0)
            {
                CfOut(OUTPUT_LEVEL_ERROR, "rename", "!! Could not rename from old key format (%s) to new (%s)", oldname, newname);
            }
        }
        else                    // we don't know the digest (e.g. because we are a client and
            // have no lastseen-map and/or root-SHA...pub of the server's key
            // yet) Just using old file format (root-IP.pub) without renaming for now.
        {
            CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Could not map key file to new format - we have no digest yet (using %s)",
                  oldname);
            snprintf(newname, sizeof(newname), "%s", oldname);
        }
    }

    if ((fp = fopen(newname, "r")) == NULL)
    {
        CfOut(OUTPUT_LEVEL_ERROR, "fopen", "Couldn't find a public key (%s)", newname);
        return NULL;
    }

    if ((newkey = PEM_read_RSAPublicKey(fp, NULL, NULL, passphrase)) == NULL)
    {
        err = ERR_get_error();
        CfOut(OUTPUT_LEVEL_ERROR, "PEM_read", "Error reading Private Key = %s\n", ERR_reason_error_string(err));
        fclose(fp);
        return NULL;
    }

    fclose(fp);

    if ((BN_num_bits(newkey->e) < 2) || (!BN_is_odd(newkey->e)))
    {
        FatalError("RSA Exponent too small or not odd");
    }

    return newkey;
}
Example #18
0
bool read_rsa_public_key(connection_t *c) {
    FILE *fp;
    char *pubname;
    char *hcfname;
    char *key;

    if(!c->rsa_key) {
        c->rsa_key = RSA_new();
//		RSA_blinding_on(c->rsa_key, NULL);
    }

    /* First, check for simple PublicKey statement */

    if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) {
        if(BN_hex2bn(&c->rsa_key->n, key) != strlen(key)) {
            logger(LOG_ERR, "Invalid PublicKey for %s!", c->name);
            return false;
        }
        BN_hex2bn(&c->rsa_key->e, "FFFF");
        free(key);
        return true;
    }

    /* Else, check for PublicKeyFile statement and read it */

    if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &pubname)) {
        fp = fopen(pubname, "r");

        if(!fp) {
            logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
            free(pubname);
            return false;
        }

        c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
        fclose(fp);

        if(c->rsa_key) {
            free(pubname);
            return true;		/* Woohoo. */
        }

        /* If it fails, try PEM_read_RSA_PUBKEY. */
        fp = fopen(pubname, "r");

        if(!fp) {
            logger(LOG_ERR, "Error reading RSA public key file `%s': %s", pubname, strerror(errno));
            free(pubname);
            return false;
        }

        c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
        fclose(fp);

        if(c->rsa_key) {
//				RSA_blinding_on(c->rsa_key, NULL);
            free(pubname);
            return true;
        }

        logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s", pubname, strerror(errno));
        free(pubname);
        return false;
    }

    /* Else, check if a harnessed public key is in the config file */

    xasprintf(&hcfname, "%s/hosts/%s", confbase, c->name);
    fp = fopen(hcfname, "r");

    if(!fp) {
        logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
        free(hcfname);
        return false;
    }

    c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL);
    fclose(fp);

    if(c->rsa_key) {
        free(hcfname);
        return true;
    }

    /* Try again with PEM_read_RSA_PUBKEY. */

    fp = fopen(hcfname, "r");

    if(!fp) {
        logger(LOG_ERR, "Error reading RSA public key file `%s': %s", hcfname, strerror(errno));
        free(hcfname);
        return false;
    }

    free(hcfname);
    c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL);
//	RSA_blinding_on(c->rsa_key, NULL);
    fclose(fp);

    if(c->rsa_key)
        return true;

    logger(LOG_ERR, "No public key for %s specified!", c->name);

    return false;
}
Example #19
0
int
read_key_pem(FILE *fp, PyObject **py_private_key_ccn,
		PyObject **py_public_key_ccn, PyObject **py_public_key_digest,
		int *public_key_digest_len)
{
	RSA *private_key_rsa = NULL;
	PyObject *py_private_key = NULL, *py_public_key = NULL;
	unsigned long err, reason;
	fpos_t fpos;
	int r;
	int public_only;

	r = fgetpos(fp, &fpos);
	JUMP_IF_NEG(r, errno_error);

	private_key_rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
	if (private_key_rsa) {
		public_only = 0;
		goto success;
	}

	err = ERR_get_error();
	reason = ERR_GET_REASON(err);

	/* 108 was meaning that start line isn't recognized */
	if (reason == 108) {
		r = fsetpos(fp, &fpos);
		JUMP_IF_NEG(r, errno_error);

		private_key_rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
		if (private_key_rsa) {
			public_only = 1;
			goto success;
		}

		err = ERR_get_error();
		reason = ERR_GET_REASON(err);
	}

	{
		char buf[256];

		ERR_error_string_n(err, buf, sizeof(buf));
		PyErr_Format(g_PyExc_CCNKeyError, "Unable to read Private Key: %s",
				buf);
		goto error;
	}

success:

	r = ccn_keypair_from_rsa(public_only, private_key_rsa, py_private_key_ccn,
			py_public_key_ccn);
	JUMP_IF_NEG(r, error);

	r = create_public_key_digest(private_key_rsa, py_public_key_digest,
			public_key_digest_len);
	JUMP_IF_NEG(r, error);

	RSA_free(private_key_rsa);

	return 0;

errno_error:
	PyErr_SetFromErrno(PyExc_IOError);
error:
	Py_XDECREF(py_private_key);
	Py_XDECREF(py_public_key);
	if (private_key_rsa)
		RSA_free(private_key_rsa);
	return -1;
}
Example #20
0
/**
 * @return true the error is not so severe that we must stop
 */
bool LoadSecretKeys(void)
{
    {
        char *privkeyfile = PrivateKeyFile(GetWorkDir());
        FILE *fp = fopen(privkeyfile, "r");
        if (!fp)
        {
            Log(CryptoGetMissingKeyLogLevel(),
                "Couldn't find a private key at '%s', use cgn-key to get one. (fopen: %s)",
                privkeyfile, GetErrorStr());
            free(privkeyfile);
            return false;
        }

        PRIVKEY = PEM_read_RSAPrivateKey(fp, NULL, NULL, (void*) priv_passphrase);
        if (PRIVKEY == NULL)
        {
            Log(LOG_LEVEL_VERBOSE, "Error reading private key. (PEM_read_RSAPrivateKey: %s)",
                CryptoLastErrorString());
            PRIVKEY = NULL;
            fclose(fp);
            return false;
        }

        fclose(fp);
        Log(LOG_LEVEL_VERBOSE, "Loaded private key at '%s'", privkeyfile);
        free(privkeyfile);
    }

    {
        char *pubkeyfile = PublicKeyFile(GetWorkDir());
        FILE *fp = fopen(pubkeyfile, "r");
        if (!fp)
        {
            Log(CryptoGetMissingKeyLogLevel(),
                "Couldn't find a public key at '%s', use cgn-key to get one (fopen: %s)",
                pubkeyfile, GetErrorStr());
            free(pubkeyfile);
            return false;
        }

        PUBKEY = PEM_read_RSAPublicKey(fp, NULL, NULL, (void*) priv_passphrase);
        if (NULL == PUBKEY)
        {
            Log(LOG_LEVEL_ERR,
                "Error reading public key at '%s'. (PEM_read_RSAPublicKey: %s)",
                pubkeyfile, CryptoLastErrorString());
            fclose(fp);
            free(pubkeyfile);
            return false;
        }

        Log(LOG_LEVEL_VERBOSE, "Loaded public key '%s'", pubkeyfile);
        free(pubkeyfile);
        fclose(fp);
    }

    if (NULL != PUBKEY
        && ((BN_num_bits(PUBKEY->e) < 2) || (!BN_is_odd(PUBKEY->e))))
    {
        Log(LOG_LEVEL_ERR, "The public key RSA exponent is too small or not odd");
        return false;
    }

    return true;
}
/* Well, almost clean copy of read_rsa_public_key */
static bool read_rsa_public_key_offline(const char *nodename, RSA **outkey) {
	avl_tree_t *t;
	FILE *fp;
	char *tname, *fname;
	char *key;
	bool x;
	RSA *rsa_key = NULL;

	init_configuration(&t);
	xasprintf(&tname, "%s/hosts/%s", confbase, nodename);
	x = read_config_file(t, tname);
	if (!x) goto _fail;

	if(!rsa_key) {
		rsa_key = RSA_new();
//		RSA_blinding_on(c->rsa_key, NULL);
	}

	/* First, check for simple PublicKey statement */

	if(get_config_string(lookup_config(t, "PublicKey"), &key)) {
		BN_hex2bn(&rsa_key->n, key);
		BN_hex2bn(&rsa_key->e, "FFFF");
		free(key);
		*outkey = rsa_key;
		goto _done;
	}

	/* Else, check for PublicKeyFile statement and read it */

	if(get_config_string(lookup_config(t, "PublicKeyFile"), &fname)) {
		fp = fopen(fname, "r");

		if(!fp) {
			logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
				   fname, strerror(errno));
			free(fname);
			goto _fail;
		}

		free(fname);
		rsa_key = PEM_read_RSAPublicKey(fp, &rsa_key, NULL, NULL);
		fclose(fp);

		if(rsa_key) {
			*outkey = rsa_key;
			goto _done;		/* Woohoo. */
		}

		/* If it fails, try PEM_read_RSA_PUBKEY. */
		fp = fopen(fname, "r");

		if(!fp) {
			logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
				   fname, strerror(errno));
			free(fname);
			goto _fail;
		}

		free(fname);
		rsa_key = PEM_read_RSA_PUBKEY(fp, &rsa_key, NULL, NULL);
		fclose(fp);

		if(rsa_key) {
//				RSA_blinding_on(c->rsa_key, NULL);
			*outkey = rsa_key;
			goto _done;
		}

		logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
			   fname, strerror(errno));
		goto _fail;
	}

	/* Else, check if a harnessed public key is in the config file */

	xasprintf(&fname, "%s/hosts/%s", confbase, nodename);
	fp = fopen(fname, "r");

	if(fp) {
		rsa_key = PEM_read_RSAPublicKey(fp, &rsa_key, NULL, NULL);
		fclose(fp);
	}

	free(fname);

	if(rsa_key) {
		*outkey = rsa_key;
		goto _done;
	}

	/* Try again with PEM_read_RSA_PUBKEY. */

	xasprintf(&fname, "%s/hosts/%s", confbase, nodename);
	fp = fopen(fname, "r");

	if(fp) {
		rsa_key = PEM_read_RSA_PUBKEY(fp, &rsa_key, NULL, NULL);
//		RSA_blinding_on(c->rsa_key, NULL);
		fclose(fp);
	}

	free(fname);

	if(rsa_key) {
		*outkey = rsa_key;
		goto _done;
	}

	logger(LOG_ERR, "No public key for %s specified!", nodename);

_fail:	
	exit_configuration(&t);
	free(tname);
	return false;

_done:	
	exit_configuration(&t);
	free(tname);
	return true;
}
Example #22
0
RSA *HavePublicKey(const char *username, const char *ipaddress, const char *digest)
{
    char keyname[CF_MAXVARSIZE], newname[CF_BUFSIZE], oldname[CF_BUFSIZE];
    struct stat statbuf;
    static char *passphrase = "public";
    unsigned long err;
    FILE *fp;
    RSA *newkey = NULL;

    snprintf(keyname, CF_MAXVARSIZE, "%s-%s", username, digest);

    snprintf(newname, CF_BUFSIZE, "%s/ppkeys/%s.pub", CFWORKDIR, keyname);
    MapName(newname);

    if (stat(newname, &statbuf) == -1)
    {
        Log(LOG_LEVEL_VERBOSE, "Did not find new key format '%s'", newname);
        snprintf(oldname, CF_BUFSIZE, "%s/ppkeys/%s-%s.pub", CFWORKDIR, username, ipaddress);
        MapName(oldname);

        Log(LOG_LEVEL_VERBOSE, "Trying old style '%s'", oldname);

        if (stat(oldname, &statbuf) == -1)
        {
            Log(LOG_LEVEL_DEBUG, "Did not have old-style key '%s'", oldname);
            return NULL;
        }

        if (strlen(digest) > 0)
        {
            Log(LOG_LEVEL_INFO, "Renaming old key from '%s' to '%s'", oldname, newname);

            if (rename(oldname, newname) != 0)
            {
                Log(LOG_LEVEL_ERR, "Could not rename from old key format '%s' to new '%s'. (rename: %s)", oldname, newname, GetErrorStr());
            }
        }
        else                    // we don't know the digest (e.g. because we are a client and
            // have no lastseen-map and/or root-SHA...pub of the server's key
            // yet) Just using old file format (root-IP.pub) without renaming for now.
        {
            Log(LOG_LEVEL_VERBOSE, "Could not map key file to new format - we have no digest yet (using %s)",
                  oldname);
            snprintf(newname, sizeof(newname), "%s", oldname);
        }
    }

    if ((fp = fopen(newname, "r")) == NULL)
    {
        Log(LOG_LEVEL_ERR, "Couldn't find a public key '%s'. (fopen: %s)", newname, GetErrorStr());
        return NULL;
    }

    if ((newkey = PEM_read_RSAPublicKey(fp, NULL, NULL, passphrase)) == NULL)
    {
        err = ERR_get_error();
        Log(LOG_LEVEL_ERR, "Error reading public key. (PEM_read_RSAPublicKey: %s)", ERR_reason_error_string(err));
        fclose(fp);
        return NULL;
    }

    fclose(fp);

    if ((BN_num_bits(newkey->e) < 2) || (!BN_is_odd(newkey->e)))
    {
        Log(LOG_LEVEL_ERR, "RSA Exponent too small or not odd");
        RSA_free(newkey);
        return NULL;
    }

    return newkey;
}
Example #23
0
void LoadSecretKeys()
{
    FILE *fp;
    static char *passphrase = "Cfengine passphrase", name[CF_BUFSIZE], source[CF_BUFSIZE];
    char guard[CF_MAXVARSIZE];
    unsigned char digest[EVP_MAX_MD_SIZE + 1];
    unsigned long err;
    struct stat sb;

    if ((fp = fopen(PrivateKeyFile(), "r")) == NULL)
    {
        CfOut(OUTPUT_LEVEL_INFORM, "fopen", "Couldn't find a private key (%s) - use cf-key to get one", PrivateKeyFile());
        return;
    }

    if ((PRIVKEY = PEM_read_RSAPrivateKey(fp, (RSA **) NULL, NULL, passphrase)) == NULL)
    {
        err = ERR_get_error();
        CfOut(OUTPUT_LEVEL_ERROR, "PEM_read", "Error reading Private Key = %s\n", ERR_reason_error_string(err));
        PRIVKEY = NULL;
        fclose(fp);
        return;
    }

    fclose(fp);

    CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Loaded private key %s\n", PrivateKeyFile());

    if ((fp = fopen(PublicKeyFile(), "r")) == NULL)
    {
        CfOut(OUTPUT_LEVEL_ERROR, "fopen", "Couldn't find a public key (%s) - use cf-key to get one", PublicKeyFile());
        return;
    }

    if ((PUBKEY = PEM_read_RSAPublicKey(fp, NULL, NULL, passphrase)) == NULL)
    {
        err = ERR_get_error();
        CfOut(OUTPUT_LEVEL_ERROR, "PEM_read", "Error reading Private Key = %s\n", ERR_reason_error_string(err));
        PUBKEY = NULL;
        fclose(fp);
        return;
    }

    CfOut(OUTPUT_LEVEL_VERBOSE, "", " -> Loaded public key %s\n", PublicKeyFile());
    fclose(fp);

    if ((BN_num_bits(PUBKEY->e) < 2) || (!BN_is_odd(PUBKEY->e)))
    {
        FatalError("RSA Exponent too small or not odd");
    }

    if (NULL_OR_EMPTY(POLICY_SERVER))
    {
        snprintf(name, CF_MAXVARSIZE - 1, "%s%cpolicy_server.dat", CFWORKDIR, FILE_SEPARATOR);

        if ((fp = fopen(name, "r")) != NULL)
        {
            if (fscanf(fp, "%4095s", POLICY_SERVER) != 1)
            {
                CfDebug("Couldn't read string from policy_server.dat");
            }
            fclose(fp);
        }
    }

/* Check that we have our own SHA key form of the key in the IP on the hub */

    char buffer[EVP_MAX_MD_SIZE * 4];

    HashPubKey(PUBKEY, digest, CF_DEFAULT_DIGEST);
    snprintf(name, CF_MAXVARSIZE, "%s/ppkeys/%s-%s.pub", CFWORKDIR, "root", HashPrintSafe(CF_DEFAULT_DIGEST, digest, buffer));
    MapName(name);

    snprintf(source, CF_MAXVARSIZE, "%s/ppkeys/localhost.pub", CFWORKDIR);
    MapName(source);

// During bootstrap we need the pre-registered IP/hash pair on the hub

    snprintf(guard, sizeof(guard), "%s/state/am_policy_hub", CFWORKDIR);
    MapName(guard);

// need to use cf_stat

    if ((stat(name, &sb) == -1) && (stat(guard, &sb) != -1))
        // copy localhost.pub to root-HASH.pub on policy server
    {
        LastSaw(POLICY_SERVER, digest, LAST_SEEN_ROLE_CONNECT);

        if (!LinkOrCopy(source, name, false))
        {
            CfOut(OUTPUT_LEVEL_ERROR, "", " -> Unable to clone server's key file as %s\n", name);
        }
    }

}
Example #24
0
int
ca_validate_pubkey(struct iked *env, struct iked_static_id *id,
    void *data, size_t len)
{
	BIO		*rawcert = NULL;
	RSA		*peerrsa = NULL, *localrsa = NULL;
	EVP_PKEY	*peerkey = NULL, *localkey = NULL;
	int		 ret = -1;
	FILE		*fp = NULL;
	char		 idstr[IKED_ID_SIZE];
	char		 file[PATH_MAX];
	struct iked_id	 idp;

	if (len == 0 && data == NULL)
		return (-1);

	switch (id->id_type) {
	case IKEV2_ID_IPV4:
	case IKEV2_ID_FQDN:
	case IKEV2_ID_UFQDN:
	case IKEV2_ID_IPV6:
		break;
	default:
		/* Some types like ASN1_DN will not be mapped to file names */
		return (-1);
	}

	bzero(&idp, sizeof(idp));
	if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL)
		goto done;

	idp.id_type = id->id_type;
	idp.id_offset = id->id_offset;
	if (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1)
		goto done;

	if (len == 0) {
		/* Data is already an public key */
		peerkey = (EVP_PKEY *)data;
	} else {
		if ((rawcert = BIO_new_mem_buf(data, len)) == NULL)
			goto done;

		if ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL)) == NULL)
			goto sslerr;
		if ((peerkey = EVP_PKEY_new()) == NULL)
			goto sslerr;
		if (!EVP_PKEY_set1_RSA(peerkey, peerrsa))
			goto sslerr;
	}

	lc_string(idstr);
	if (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) ||
	    strlcat(file, idstr, sizeof(file)) >= sizeof(file))
		goto done;

	if ((fp = fopen(file, "r")) == NULL)
		goto done;
	localkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
	if (localkey == NULL) {
		/* reading PKCS #8 failed, try PEM */
		rewind(fp);
		localrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
		fclose(fp);
		if (localrsa == NULL)
			goto sslerr;
		if ((localkey = EVP_PKEY_new()) == NULL)
			goto sslerr;
		if (!EVP_PKEY_set1_RSA(localkey, localrsa))
			goto sslerr;
	} else {
		fclose(fp);
	}
	if (localkey == NULL)
		goto sslerr;

	if (!EVP_PKEY_cmp(peerkey, localkey))
		goto done;

	log_debug("%s: valid public key in file %s", __func__, file);

	ret = 0;
 sslerr:
	if (ret != 0)
		ca_sslerror(__func__);
 done:
	ibuf_release(idp.id_buf);
	if (peerkey != NULL)
		EVP_PKEY_free(peerkey);
	if (localkey != NULL)
		EVP_PKEY_free(localkey);
	if (peerrsa != NULL)
		RSA_free(peerrsa);
	if (localrsa != NULL)
		RSA_free(localrsa);
	if (rawcert != NULL)
		BIO_free(rawcert);

	return (ret);
}
Example #25
0
   int send_file(char* file_name, int sk) {
	  
	FILE* file;

	FILE* fp;

	int name_size;			// size of the name of the file to be sent
	int size,k_size; 			// size of the file to be sent
	int ret, i; 			
	unsigned char* buffer;		// pointer to the buffer containing the file
	char* sym_key;

	int enckeysize;

	int remote_random,local_random;

char* password;

	//***** recieve the random value from server *****//

	ret = recv(sk, &remote_random, sizeof(int), MSG_WAITALL);


	file = fopen("key","r");

	/* Retrieve the size of the key to be sent */
	fseek(file,0,SEEK_END);
	k_size = ftell(file);

	/* Memory allocation for the key to be sent */
	sym_key = malloc(k_size * sizeof (char));
	fseek(file, 0, SEEK_SET);

	/* Read key from file */
	ret = fread(sym_key, 1, k_size, file);

	
//***** RSA ENCRYPTION PART BEGIN *****//

	char* enckey;

	RSA* rsa = RSA_new();

	fp = fopen("pub.pem","r");

	PEM_read_RSAPublicKey(fp,&rsa,NULL,NULL);

	enckeysize =RSA_size(rsa); 

	enckey=malloc(enckeysize * sizeof(char));

	RSA_encrypt(sym_key,enckey,k_size,rsa);

	fclose(fp);

//*** RSA ENCRYPTION PART end ***//
	
	/* Computation of the length of the filename */
	name_size = strlen(file_name);

	/* Open the file to be sent */
	file = fopen(file_name,"r");
	if(file == NULL) {
	  printf("\nError opening the file file\n");
	  return 1;
	}
    	
    	/* Retrieve the size of the file to be sent */
	fseek(file,0,SEEK_END);
	size = ftell(file);
	
	/* Memory allocation for the file to be sent */
	buffer = malloc(size * sizeof (char));
	fseek(file, 0, SEEK_SET);

	/* File reading */
	ret = fread(buffer, 1, size, file);
	  if(ret < size) {
	  printf("\n Error reading the file \n");
	  return 1;
	}
	
	fclose(file);
	
	/* The length of the file name is sent */
	ret = send(sk, &name_size, sizeof(name_size), 0);
 
	if(ret != sizeof(name_size)){
	  printf("\n Error trasmitting the length of the file name\n ");
	  return 1;
	}
    
	/* The file name is sent */
	ret = send(sk, file_name, name_size, 0); 
	if(ret < name_size){
	  printf("\n Error transmitting the file name\n ");
	  return 1;
	}
		


//****** Generate hash for freshness and origin(password) check *****//

	time_t t;
	int password_size;
	int fresh_size;
	char* fresh_txt;

	t = time(NULL);

 	srand ( time(NULL));

	local_random = rand();

	file = fopen("passofA.txt","r");

	fseek(file,0,SEEK_END);

	password_size = ftell(file);

	password = malloc(password_size * sizeof (char));

	fseek(file, 0, SEEK_SET);

	ret = fread(password, 1, password_size, file);
	
	fclose(file);

	int pass_hash_len;

	const EVP_MD *md1;

	md1 = EVP_get_digestbyname("sha1");

	unsigned char pass_md_value[EVP_MD_size(md1)];

	pass_hash_len=hash_gen(password,&pass_md_value[0]);

	fresh_size=sizeof(password)+sizeof(local_random)+sizeof(remote_random);
	
	fresh_txt = malloc(fresh_size);

	int loc_rand_size=sizeof(local_random);

	int rem_rand_size = sizeof(remote_random);

	memcpy(fresh_txt,&pass_md_value[0],pass_hash_len);

	memcpy(&fresh_txt[pass_hash_len],&local_random,loc_rand_size);

	memcpy(&fresh_txt[pass_hash_len+loc_rand_size],&remote_random,rem_rand_size);

	const EVP_MD *md;

	md = EVP_get_digestbyname("sha1");

	unsigned char md_value[EVP_MD_size(md)];
	
	int md_len;

	md_len=hash_gen(fresh_txt,&md_value[0]);

	printf("\n Freshness Digest is: \n");
        for(i = 0; i < md_len; i++) printbyte(md_value[i]);
        printf("\n");



///*** SYMMETRIC KEY ENCRYPTION PART BEGIN ***///

	char* totbuffer;
	int  nctot;
	char *plaintext, *ciphertext;
	int totbufsize = size+md_len;

	totbuffer = malloc(totbufsize);

	// message + digest for freshness and password 
	memcpy(totbuffer,buffer,size);  

	memcpy(&totbuffer[size],md_value,md_len);

	ciphertext = malloc(totbufsize+128);

	nctot = symmetric_encrypt(totbuffer,ciphertext,totbufsize); //  encrypted size


//***** SYMMETRIC KEY encryption part END *****///



//***** concatenate enckey and ciphertext *****//

	char* textnkeynhash;
	int totsize;

	totsize=nctot+enckeysize+loc_rand_size;
	
	textnkeynhash=malloc(totsize);
	
	memcpy(textnkeynhash,ciphertext,nctot);

	memcpy(&textnkeynhash[nctot],enckey,enckeysize);

	memcpy(&textnkeynhash[nctot+enckeysize],&local_random,loc_rand_size);


	/* The file size is sent */
	ret = send(sk, &totsize, sizeof(totsize), 0);
	  if(ret != sizeof(size)){
	  printf("\n Error transmitting the file size\n ");
	  return 1;
	}

	/* The file is sent */
	ret = send(sk, textnkeynhash, totsize, 0);
	if(ret < size){
	  printf("\n Error transmitting the file\n");
	  return 1;
	}
	
	printf("\n File %s with size %d bytes has been sent\n", file_name, totsize);
	free(buffer);
	free(ciphertext);
    
	return 0;
	
}
Example #26
0
		inline rsa_key rsa_key::from_public_key(file _file, pem_passphrase_callback_type callback, void* callback_arg)
		{
			return take_ownership(PEM_read_RSAPublicKey(_file.raw(), NULL, callback, callback_arg));
		}
Example #27
0
/**
 * @brief Search for a key:
 *        1. username-hash.pub
 *        2. username-ip.pub
 * @return NULL if key not found in any form
 */
RSA *HavePublicKey(const char *username, const char *ipaddress, const char *digest)
{
    char keyname[CF_MAXVARSIZE], newname[CF_BUFSIZE], oldname[CF_BUFSIZE];
    struct stat statbuf;
    FILE *fp;
    RSA *newkey = NULL;

    snprintf(keyname, CF_MAXVARSIZE, "%s-%s", username, digest);

    snprintf(newname, CF_BUFSIZE, "%s/ppkeys/%s.pub", CFWORKDIR, keyname);
    MapName(newname);

    if (stat(newname, &statbuf) == -1)
    {
        Log(LOG_LEVEL_VERBOSE, "Did not find new key format '%s'", newname);

        snprintf(oldname, CF_BUFSIZE, "%s/ppkeys/%s-%s.pub",
                 CFWORKDIR, username, ipaddress);
        MapName(oldname);
        Log(LOG_LEVEL_VERBOSE, "Trying old style '%s'", oldname);

        if (stat(oldname, &statbuf) == -1)
        {
            Log(LOG_LEVEL_DEBUG, "Did not have old-style key '%s'", oldname);
            return NULL;
        }

        if (strlen(digest) > 0)
        {
            Log(LOG_LEVEL_INFO, "Renaming old key from '%s' to '%s'", oldname, newname);

            if (rename(oldname, newname) != 0)
            {
                Log(LOG_LEVEL_ERR, "Could not rename from old key format '%s' to new '%s'. (rename: %s)", oldname, newname, GetErrorStr());
            }
        }
        else
        {
            /* We don't know the digest (e.g. because we are a client and have
               no lastseen-map yet), so we're using old file format
               (root-IP.pub). */
            Log(LOG_LEVEL_VERBOSE,
                "We have no digest yet, using old keyfile name: %s",
                oldname);
            snprintf(newname, sizeof(newname), "%s", oldname);
        }
    }

    if ((fp = fopen(newname, "r")) == NULL)
    {
        Log(CryptoGetMissingKeyLogLevel(), "Couldn't find a public key '%s'. (fopen: %s)", newname, GetErrorStr());
        return NULL;
    }

    if ((newkey = PEM_read_RSAPublicKey(fp, NULL, NULL,
                                        (void *)pub_passphrase)) == NULL)
    {
        Log(LOG_LEVEL_ERR,
            "Error reading public key. (PEM_read_RSAPublicKey: %s)",
            CryptoLastErrorString());
        fclose(fp);
        return NULL;
    }

    fclose(fp);

    if ((BN_num_bits(newkey->e) < 2) || (!BN_is_odd(newkey->e)))
    {
        Log(LOG_LEVEL_ERR, "RSA Exponent too small or not odd");
        RSA_free(newkey);
        return NULL;
    }

    return newkey;
}