parseTicket.c   [plain text]


#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/sha.h>
#include "AppleMobilePersonalizedTicket.h"
#include <libDER/libDER.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_Decode.h>
#include <libDER/DER_Encode.h>
#include <libDER/DER_Keys.h>
#include <libDER/oids.h>
#include "DER_Ticket.h"

const unsigned char GoldKeyCert[] = {
0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00,
0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x31, 0x6e, 0xc6, 0x4f,
0xf1, 0xe8, 0x7d, 0x81, 0x38, 0x6d, 0xd8, 0xb3,
0x2b, 0xe4, 0xb5, 0xa0, 0x09, 0xaf, 0x74, 0xdd,
0xe9, 0x60, 0x27, 0x42, 0x07, 0xa3, 0xac, 0xef,
0xe5, 0x75, 0x07, 0xa8, 0xc2, 0x2c, 0x25, 0x56,
0x91, 0x37, 0xea, 0xdb, 0xdb, 0x68, 0x4a, 0x1c,
0xe3, 0x29, 0x61, 0x85, 0xd7, 0xd8, 0x66, 0x86,
0x66, 0xbf, 0xbf, 0x98, 0xae, 0xb4, 0xe9, 0x6c,
0x13, 0x81, 0x97, 0x78, 0x2a, 0x8d, 0xdc, 0x37,
0x9a, 0xf1, 0xa4, 0x0a, 0x9d, 0x74, 0xd5, 0x72,
0xbc, 0xb5, 0x64, 0xa6, 0x1a, 0x62, 0xd5, 0x39,
0xfb, 0x6f, 0xc0, 0xd1, 0xc7, 0x93, 0xc3, 0x20,
0xda, 0x84, 0x69, 0x1e, 0xd9, 0x96, 0x2e, 0xc1,
0x4f, 0x28, 0x96, 0x14, 0xa4, 0x68, 0x0a, 0x40,
0xe5, 0x17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 0xb6, 0xc5, 0x10, 0x0c,
0xea, 0x5b, 0xcc, 0xaf, 0xee, 0x7b, 0x15, 0x4e,
0x4e, 0x3c, 0x29, 0x9c, 0xf8, 0xe6, 0x59, 0xca,
0xaf, 0x48, 0x12, 0x99, 0x76, 0xde, 0x54, 0xe2,
0x75, 0x62, 0x31, 0x17,
};

#define SIG_LEN     128
#define HASH_LEN    20

const unsigned char fakeAlgOID[] = {
0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05
};

const unsigned char fakeG3Cert[] = {
0x01,0x00,0x00,0x00,
0x1c,0x00,0x00,0x00,
0x01,0x08,0x00,0x00,
0x10,0x0a,0x00,0x00,
0x00,0x00,0x00,0x00,
0x00,0x04,0x00,0x00,
0x01,0x00,0x01,0x00,
0x19,0xfc,0xb6,0x7b,0x4e,0xa8,0xd7,0xb1,0xeb,0xf9,0x19,0x28,0x07,0x7f,0x47,0x4c,
0xe1,0x9f,0xbe,0x01,0x15,0x5c,0xea,0xda,0xc3,0xd1,0x59,0x3c,0x75,0xed,0x00,0x7b,
0x22,0x67,0x22,0xd6,0xd3,0xee,0xc2,0x04,0xdf,0x47,0xc4,0x85,0xc0,0x56,0xa4,0x8d,
0xf3,0xf0,0xcf,0x00,0x9d,0xd2,0x03,0xc1,0x23,0x3f,0xc8,0x9f,0xef,0xfe,0xea,0x50,
0x33,0x6b,0xbe,0x74,0x1a,0xa3,0x3c,0x13,0xa2,0xc5,0xf6,0x75,0x88,0x1d,0x3f,0xba,
0xff,0x0d,0x47,0xab,0xbe,0xfe,0x42,0xd3,0xea,0xe2,0xe2,0xb0,0x06,0xd7,0x88,0xf8,
0x1d,0x93,0xdf,0x86,0xbd,0xd8,0xa8,0x5f,0x2b,0xe3,0x97,0x41,0xa1,0xc6,0x1d,0x69,
0xe9,0x88,0xdf,0x87,0xbb,0x1b,0xff,0x31,0x82,0xae,0x8a,0x69,0x31,0xca,0xc3,0x90,
0x0f,0x0d,0x22,0xa3,0x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6,0xd0,0x49,0x40,0xab,0xbe,0xf7,0x43,0x02,0x96,0xf0,0x74,0xa5,0x7d,
0x68,0x89,0xfa,0x58, 0xad, 0x7b, 0x2f, 0x7d, 0xe8, 0x21, 0x34, 0x5e, 0x6c, 0x20,
0x97, 0x9e
};

const unsigned char fakeSig[] = {
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
};

static void
dumpBytes( const char *title, const unsigned char *data, int len, int nonewline );

static int
rsa_sign(
    const char *keyFile,
    unsigned char *plain,
    unsigned plainLength,
    unsigned char signature[SIG_LEN] )
{
    int rc = -1;
    FILE *fp = NULL;
    RSA *rsa = NULL;
    unsigned signatureLength = 0;

    fp = fopen ( (char*) keyFile, "r" );
    if ( !fp ) {
        fprintf( stderr, "failed to open file=%s\n", keyFile );
        goto cleanup;
    }
    rsa = RSA_new();
    if ( !rsa ) {
        fprintf( stderr, "RSA_new() failed\n" );
        goto cleanup;
    }
    rsa = (RSA*)PEM_read_RSAPrivateKey( fp, &rsa, NULL, NULL );
    if ( !rsa ) {
        fprintf( stderr, "PEM_read_RSAPrivateKey() failed\n" );
        goto cleanup;
    }
    signatureLength = SIG_LEN;
    char sha1[20] = {};
    (void) SHA1( plain, plainLength, (unsigned char*)sha1 );
    rc = RSA_sign( NID_sha1, (unsigned char*)sha1, sizeof( sha1),
        signature, &signatureLength, rsa );
    if ( rc != 1 ) {
        fprintf(stderr, "RSA_sign failed=%d\n", rc );
        rc = -1;
        goto cleanup;
    } else {
        rc = 0;
    }

cleanup:
    if ( fp ) fclose( fp );
    RSA_free( rsa );
    return rc;
}

static int
rsa_verify(
    const char *keyFile,
    unsigned char *plain,
    unsigned plainLength,
    unsigned char signature[SIG_LEN] )
{
    int rc = -1;
    FILE *fp = NULL;
    RSA *rsa = NULL;
    unsigned signatureLength = 0;

    fp = fopen ( (char*) keyFile, "r" );
    if ( !fp ) {
        fprintf( stderr, "failed to open file=%s\n", keyFile );
        goto cleanup;
    }
    rsa = RSA_new();
    if ( !rsa ) {
        fprintf( stderr, "RSA_new() failed\n" );
        goto cleanup;
    }
    rsa = (RSA*)PEM_read_RSAPrivateKey( fp, &rsa, NULL, NULL );
    if ( !rsa ) {
        fprintf( stderr, "PEM_read_RSAPrivateKey() failed\n" );
        goto cleanup;
    }
    signatureLength = SIG_LEN;
    char sha1[20] = {};
    (void) SHA1( plain, plainLength, (unsigned char*)sha1 );
    rc = RSA_verify( NID_sha1, (unsigned char*)sha1, sizeof( sha1 ),
        signature, signatureLength, rsa );
    if ( rc != 1 ) {
        fprintf(stderr, "RSA_verify failed=%d\n", rc );
        rc = -1;
        goto cleanup;
    } else {
        rc = 0;
    }

cleanup:
    if ( fp ) fclose( fp );
    RSA_free( rsa );
    return rc;
    return rc;
}

static void
dumpBytes( const char *title, const unsigned char *data, int len, int nonewline )
{
    int width = 16;
    int line = 0;
    int multiple = 0;

    multiple = ( len % width == 0 );

    printf( "[%s: %d bytes]\n", title, len );
    while ( len-- > 0 ) {
        line++;
        printf( "%02X ", *data++ );
        if ( line % width == 0 && len > 0 && !nonewline ) {
            printf( "\n" );
        }
    }

    printf("\n");
}

static void
readFile(char *filename, unsigned char **data, unsigned *len)
{
    int size = 0;
    FILE *file = NULL;
    if ((file = fopen(filename, "r")) == NULL) {
        fprintf(stderr, "could not open file=%s", filename);
        return;
    }
    fseek(file, 0, SEEK_END);
    size = ftell(file);
    *len = size;
    *data = (unsigned char*)malloc(*len);
    if (!*data) {
        fprintf(stderr, "Out of memory");
        fclose(file);
        return;
    }
    rewind(file);
    (void)fread(*data, size, 1, file);
    fclose(file);
}

static void
writeFile( char* filename, unsigned char* buf, int len )
{
    FILE *file = NULL;
    file = fopen( filename, "w" );
    if ( file ) {
        fwrite( buf, len, 1, file );
        fclose( file );
    }
}


static void
verify_bb_ticket(
    unsigned char *ticketData,
    unsigned ticketLength,
    const char *keyFile,
    bool doPrint )
{
    if ( doPrint ) {
        dumpBytes( "Ticket (whole)", ticketData, ticketLength, 0 );
        printf( "\nBreakdown:\n" );
    }

    DERItem derTicket = { .data = ticketData, .length = ticketLength };
    DERReturn drtn;
    DERBbTicket ticket = {};
    DERSize ticketSize;
    drtn = DERDecodeBbTicket(&derTicket, &ticket, &ticketSize);
    if (drtn != DR_Success) goto badTicket;
    fprintf( stderr, "ticketSize=%u\n", ticketSize );

    // Verify signature if key file exists (we should really use the certificate or GPUK in the ticket here. */
    if ( keyFile ) {
        int status =  rsa_verify(
            keyFile,
            (unsigned char *)ticket.body.data,
            ticket.body.length,
            (unsigned char *)ticket.signature.data );
        if ( status ) {
            fprintf( stderr, "rsa_verify failed=%d\n", status );
        } else {
            fprintf( stdout, "Signature verified successfully\n");
        }
    }

    /* Example of how to retrive fields from ticket. */
    DERItem snum;
    drtn = DERSetDecodeItemWithTag(&ticket.body,
        ASN1_CONTEXT_SPECIFIC | kBbSNUMTag, &snum);
    if (drtn != DR_Success) goto badTicket;
    DERItem chipId;
    drtn = DERSetDecodeItemWithTag(&ticket.body,
        ASN1_CONTEXT_SPECIFIC | kBbChipIDTag, &chipId);
    if (drtn != DR_Success) goto badTicket;

    return;
badTicket:
    fprintf( stdout, "Bad ticket\n");
    return;
}

static void
verify_ticket_file(
    const char *ticketFile,
    const char *keyFile )
{
    unsigned char *ticket = NULL;
    unsigned ticketLength = 0;
    readFile( (char*)ticketFile, &ticket, &ticketLength );
    verify_bb_ticket( ticket, ticketLength, keyFile, false );
}

static void
make_sample_ap_ticket( void )
{
    unsigned char chipId[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char ecid[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

    DERApTicket ticket = { };

    /* Encode the signatureAlgorithm field of the ticket. */
    DERAlgorithmId algorithmId = { .oid = oidSha1Rsa, .params = {} };
    ticket.signatureAlgorithm.length = DERLengthOfEncodedSequence(
        ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs,
        DERAlgorithmIdItemSpecs);
    ticket.signatureAlgorithm.data = malloc(ticket.signatureAlgorithm.length);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, ticket.signatureAlgorithm.data, &ticket.signatureAlgorithm.length);

    /* Construct ticket body. */
    DERSize numBodyItemSpecs = 0;
    DERItemSpec bodyItemSpecs[50] = {};
    DERItem bodyItems[50] = {};

    /* Add tags in sorted order. */
    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kApECIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = ecid;
    bodyItems[numBodyItemSpecs].length = sizeof(ecid);
    numBodyItemSpecs++;

    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kApChipIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = chipId;
    bodyItems[numBodyItemSpecs].length = sizeof(chipId);
    numBodyItemSpecs++;

    /* Encode ticket body. */
    ticket.body.length = DERLengthOfEncodedSequence(ASN1_CONSTR_SET,
        &bodyItems, numBodyItemSpecs, bodyItemSpecs);
    ticket.body.data = malloc(ticket.body.length);
    DEREncodeSequence(ASN1_CONSTR_SET, &bodyItems, numBodyItemSpecs,
        bodyItemSpecs, ticket.body.data, &ticket.body.length);

    // Signature
    ticket.signature.data = (DERByte *)fakeSig;
    ticket.signature.length = sizeof(fakeSig);

    // Certificates
    DERItemSpec certItemSpecs[1];
    DERItem certItems[1];
    certItemSpecs[0].offset = 0;
    certItemSpecs[0].tag = ASN1_CONSTR_SEQUENCE;
    certItemSpecs[0].options = DER_ENC_WRITE_DER;

    // NOTE: The Certificate should be added to the ticket by the host. I'm just simulating that here
    // to generate the final ticket blob.
    readFile("S5L8920_TATSU_FAC_DARWIN_DEV_CHAIN.der", &certItems[0].data, &certItems[0].length);

    ticket.certificates.length = DERLengthOfEncodedSequence(
        ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 1, &certItems,
        1, certItemSpecs);
    ticket.certificates.data = malloc(ticket.certificates.length);
    DEREncodeSequence(ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 1, &certItems,
        1, certItemSpecs, ticket.certificates.data, &ticket.certificates.length);

    /* Encode the entire ticket. */
    DERSize ticketLength = DERLengthOfEncodedSequence(ASN1_CONSTR_SEQUENCE,
        &ticket, DERNumApTicketItemSpecs, DERApTicketItemSpecs);
    DERByte *ticketBytes = malloc(ticketLength);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &ticket, DERNumApTicketItemSpecs, DERApTicketItemSpecs,
        ticketBytes, &ticketLength);

    // save ticket to file
    writeFile("ApTicket.bin", ticketBytes, ticketLength);

//cleanup:
    free(ticket.body.data);
    free(ticket.signatureAlgorithm.data);
    free(ticket.certificates.data);
    free(ticketBytes);
}

static void
make_sample_bb_ticket( void )
{
    int status = 0;
    unsigned char chipId[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char snum[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char signature[SIG_LEN] = {};
    DERByte *ticketBytes = NULL;

    DERBbTicket ticket = {};

    /* Encode the signatureAlgorithm field of the ticket. */
    DERAlgorithmId algorithmId = { .oid = oidSha1Rsa };
    ticket.signatureAlgorithm.length = DERLengthOfEncodedSequence(
        ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs,
        DERAlgorithmIdItemSpecs);
    ticket.signatureAlgorithm.data = malloc(ticket.signatureAlgorithm.length);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &algorithmId,
        DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs,
        ticket.signatureAlgorithm.data, &ticket.signatureAlgorithm.length);

    /* Construct ticket body. */
    DERSize numBodyItemSpecs = 0;
    DERItemSpec bodyItemSpecs[50] = {};
    DERItem bodyItems[50] = {};

    /* Add tags in sorted order. */
    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kBbSNUMTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = snum;
    bodyItems[numBodyItemSpecs].length = sizeof(snum);
    numBodyItemSpecs++;

    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kBbChipIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = chipId;
    bodyItems[numBodyItemSpecs].length = sizeof(chipId);
    numBodyItemSpecs++;

    /* Encode ticket body. */
    ticket.body.length = DERLengthOfEncodedSequence(ASN1_CONSTR_SET,
        &bodyItems, numBodyItemSpecs, bodyItemSpecs);
    ticket.body.data = malloc(ticket.body.length);
    DEREncodeSequence(ASN1_CONSTR_SET, &bodyItems, numBodyItemSpecs, bodyItemSpecs,
        ticket.body.data, &ticket.body.length);

    // NOTE: In the SEE machine, the Body above will then be hashed/signed to generate signature
    status =  rsa_sign(
        "G1_GPrK.pem",
        ticket.body.data,
        ticket.body.length,
        (unsigned char *)signature );
    if ( status ) {
        fprintf( stderr, "rsa_sign failed=%d\n", status );
        goto cleanup;
    } else {
        fprintf( stdout, "Signed successfully\n");
    }

    status =  rsa_verify(
        "G1_GPrK.pem",
        ticket.body.data,
        ticket.body.length,
        (unsigned char *)signature );
    if ( status ) {
        fprintf( stderr, "rsa_verify failed=%d\n", status );
        goto cleanup;
    } else {
        fprintf( stdout, "Signature verified successfully\n");
    }

    // Signature
    ticket.signature.data = signature;
    ticket.signature.length = SIG_LEN;

    // Certificates
    ticket.gpuk.length = sizeof(GoldKeyCert);
    ticket.gpuk.data = (DERByte *)GoldKeyCert;

    /* Encode the entire ticket. */
    DERSize ticketLength = DERLengthOfEncodedSequence(ASN1_CONSTR_SEQUENCE,
        &ticket, DERNumBbTicketItemSpecs, DERBbTicketItemSpecs);
    ticketBytes = malloc(ticketLength);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &ticket, DERNumBbTicketItemSpecs,
        DERBbTicketItemSpecs, ticketBytes, &ticketLength);

    // save ticket to file
    writeFile("BbTicket.bin", ticketBytes, ticketLength);

cleanup:
    free(ticket.body.data);
    free(ticket.signatureAlgorithm.data);
    free(ticketBytes);
}

static void
long_tag_test(void)
{
    printf("ASN1_TAG_MASK           0x%.016qx\n", (uint64_t)ASN1_TAG_MASK);
    printf("ASN1_TAGNUM_MASK        0x%.016qx\n", (uint64_t)ASN1_TAGNUM_MASK);
    printf("ASN1_METHOD_MASK        0x%.016qx\n", (uint64_t)ASN1_METHOD_MASK);
    printf("ASN1_PRIMITIVE          0x%.016qx\n", (uint64_t)ASN1_PRIMITIVE);
    printf("ASN1_CONSTRUCTED        0x%.016qx\n", (uint64_t)ASN1_CONSTRUCTED);
    printf("ASN1_CLASS_MASK         0x%.016qx\n", (uint64_t)ASN1_CLASS_MASK);
    printf("ASN1_UNIVERSAL          0x%.016qx\n", (uint64_t)ASN1_UNIVERSAL);
    printf("ASN1_APPLICATION        0x%.016qx\n", (uint64_t)ASN1_APPLICATION);
    printf("ASN1_CONTEXT_SPECIFIC   0x%.016qx\n", (uint64_t)ASN1_CONTEXT_SPECIFIC);
    printf("ASN1_PRIVATE            0x%.016qx\n", (uint64_t)ASN1_PRIVATE);

    DERByte buf[10];
    DERSize len = sizeof(buf);
    DERReturn drtn;
    DERTag tag = ASN1_CONTEXT_SPECIFIC | ASN1_TAGNUM_MASK;
    drtn = DEREncodeItem(tag, 0, 0, buf, &len);
    if (drtn)
    {
        printf("DEREncodeItem: %u\n", drtn);
    }
    DERItem der = { .data = buf, .length = len };

    dumpBytes("tlv", buf, len, 0);

    DERDecodedInfo decoded;
    drtn = DERDecodeItem(&der, &decoded);
    if (drtn)
    {
        printf("DERDecodeItem: %u\n", drtn);
    }
    if (decoded.tag != tag)
    {
        printf("DERDecodeItem tag: 0x%qx != 0x%qx\n", (uint64_t)decoded.tag, (uint64_t)tag);
    }
    printf("DERDecodeItem tag: 0x%qx encoded in %u bytes, decoded length: %u\n",
        (uint64_t)tag, len, decoded.content.length);
}

int main(int argc, char **argv)
{
    long_tag_test();
    printf( "=> Making sample BB ticket...\n");
    make_sample_bb_ticket();
    printf( "=> Making sample AP ticket...\n");
    make_sample_ap_ticket();
    printf( "=> Verifying signature in bb_ticket.bin ...\n");
    verify_ticket_file( "bb_ticket.bin", "G1_GPrK.pem" );
    return 0;
}