mkCmd.c 15.8 KB
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <PR/bbmetadata.h>
#include <PR/bbcert.h>
#include <PR/os_bbsa.h>
#include <bbtoolsapi.h>
#include <aes_api.h>
#include <openssl/rsa.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <bb_nn.h>
#include <sha1.h>
#include <util.h>

#define BLK_SIZE	16384
#define AES_BLOCK_SIZE  128

#define H2BE4(a) (htonl((a)))
#define H2BE2(a) (htons((a)))

#define IS_SYSAPP    (isSysapp)


/*********************************************************************

 COMMAND SYNTAX:

   mkCmd [-c contentId] [-i cmdAesIv] 
         [-d contentDescFile] [-r hwRights] [-R swRights] [-e] [-s] 
         [-l cpCrlVersion] [-L caCrlVersion]
         appInFile appAesKey appAesIv certFile appOutFile cmdOutFile

 INPUT 
 
   appInFile     - binary file, determine size from file.
  
   [-c contentId]
                 - BbContentId (u32) content id.
   [-d contentDescFile] 
                 - 10K opaque content description
                   Default to no content description, in which case
                   only a BbContentMetaDataHead is output (instead
                   of a BbContentMetadata struct).

   [-i cmdAesIv]  
                 - aes md iv used during encryption of md content key.
                   Default internally coded if not used.
  
   appAesKey     - aes content key.
   appAesIv      - aes content iv.
 
   certFile      - BbRsaCert binary input file, for signing.
 
   [-r hwRights] - enable hw runtime rights
   [-r swRights] - enable sw runtime rights

   [-e]          - flag indicating re-encryption required
                   Default recrypt NOT required.
                   
   [-s]          - flag indicating a sysapp/bootapp is being packaged.

 OUTPUT:
   
   cmdOutFile  R - content metadata binary struct, BbContentMetaData.
                          
   appOutFile  R - output app compressed and encrypted.

*********************************************************************/
#define MAX_KEY_SIZE 4096

void printUsage()
{
    fprintf(stderr, "\nPackage a rom. Usage:\n\n"
     " mkCmd [-c contentId] [-i cmdAesIv] -d contentDescFile [-r hwRights]\n"
     "    [-R swRights] [-e] [-s] [-b bbid] [-S signerKeyFile] \n"
     "    [-L caCrlVersion] [-l cpCrlVersion] [-C certSys]\n"
     "    appInFile appAesKey appAesIv certFile appOutFile cmdOutFile\n\n"
     " where -e indicates re-encryption required,\n"
     " -s indicates a bootapp/sysapp is being packaged,\n"
     " aes key/iv args are ascii strings for 16B data.\n\n");
}


int asciiToBin(char *str,int bytes,u8 *buf)
{
    int i,j;
    char t;

    for(i=0;i<bytes;i++){
        t = str[2*i];
        if ((t >= '0') && (t <= '9')) 
            j = (t - '0') << 4;
        else if ((t >= 'a') && (t <= 'f')) 
            j = (t - 'a' + 10) << 4;
        else if ((t >= 'A') && (t <= 'F')) 
            j = (t - 'A' + 10) << 4;
        else return -1;
        
        t = str[2*i+1];
        if ((t >= '0') && (t <= '9')) 
            j ^= (t - '0');
        else if ((t >= 'a') && (t <= 'f')) 
            j ^= (t - 'a' + 10);
        else if ((t >= 'A') && (t <= 'F')) 
            j ^= (t - 'A' + 10);
        else return -1;

        buf[i]=j;
    }
    
    return 0;
}

/* 
 * create unsigned  meta data blob: called by content publishing 
 */
  
int main(int argc, char* argv[]) 
{
    FILE *appInFile=NULL,*appOutFile=NULL;
    FILE *cmdOutFile=NULL,*contentDescFile=NULL;
    unsigned char signature[4096];
    int count;
    /* ascii strings for 16B aes quantities */
    char appAesKey[36],appAesIv[36],cmdAesIv[36];
    char v2Name[1024];
    int error,keyLen=128;
    AesKeyInstance key;
    AesCipherInstance cipher;
    char c;
    char ibuf[BLK_SIZE],obuf[BLK_SIZE];
    int inBytes, contentBytes;
    int recrypt = 0;
    BbContentMetaData cmd;
    BbContentId cid=0;
    u32 hwRightsFlags=0,swRightsFlags=(1<<SK_API_CALL_KEEP_ALIVE);
    unsigned char *padded_data;
    SHA1Context sha;
    RSA *prsa;
    int descflags;
    int size, i, e_size, n_size;
    unsigned char e_string[4096];
    unsigned char n_string[4096];
    unsigned char customResult[4096];
    unsigned char *verify;
    /* cert types */
    unsigned long certpublickey[128];
    unsigned long certsign[128];
    unsigned long certexponent;
    BbServerSuffix issuername;
    u8  hash[20];
    u32 bbid=0;
    u8   commonIv[16];
    u8   aesIv[16];
    u8   aesKey[16];
    int useOldKeyFile = 0;
    int isSysapp = 0;
    int injectSigError=0; 
    
    FILE *rootKeyDataFile;
    FILE *cpKeyDataFile=NULL;

    FILE *certptr=NULL;
    FILE *propptr=NULL;

    u32 properties[10];
    FILE *viragefileptr;
    char *root_string;
    char tmp_name[2048];
    u32 caCrlVersion=0;
    u32 cpCrlVersion=0;

    u32 virageconstants[30];
    u8 *buf=NULL;

    if((root_string = getenv("ROOT")) == NULL){
        fprintf(stderr,"Root not set\n");
        exit(1);
    }

    memset(virageconstants, 0, sizeof virageconstants);
    sprintf(tmp_name,"%s/usr/host_data/%s", root_string, "virage2.in");
    if((viragefileptr = fopen(tmp_name, "r")) == NULL) {
        fprintf(stderr,"Virage input file not found\n");
        return 1;
    }
    fread(virageconstants, 4, 26, viragefileptr);
    fclose(viragefileptr);

    cmdAesIv[0]='\0';

    v2Name[0]='\0';

    opterr = 0;
    while((c = getopt(argc, argv, "c:d:i:r:R:w:esb:S:C:Tp:L:l:")) != (char)-1) {
        switch(c) {
        case 'c':  /* content id */
	    cid = strtoul(optarg, 0, 0);
            break;
	case 'd':
	    if ((contentDescFile = fopen(optarg, "r")) == NULL) {
		perror(optarg);
                goto cleanup;
	    }
	    break;
        case 'i':
            strcpy(cmdAesIv,optarg);
            break;
        case 'r': 
            hwRightsFlags = strtoul(optarg, 0, 0);
            break;
        case 'R': 
            swRightsFlags = strtoul(optarg, 0, 0);
            break;
        case 'w':
            useOldKeyFile = 1;
            if((rootKeyDataFile = fopen(optarg, "r")) == NULL) {
                perror(optarg);
                goto cleanup;
            }
            break;
        case 'e':
            recrypt = BB_CMD_EXEC_RECRYPT;
            break;
        case 's':
            isSysapp = 1;
            break;
        case 'b':  /* bb id */
	    bbid = strtoul(optarg, 0, 0);
            break;
	case 'S':
	    if ((cpKeyDataFile= fopen(optarg, "r")) == NULL) {
		perror(optarg);
                goto cleanup;
	    }
	    break;
	case 'C':
	    if ((certptr= fopen(optarg, "r")) == NULL) {
		perror(optarg);
                goto cleanup;
	    }
	    break;
        case 'T':
            injectSigError = 1;
            break;
	case 'p':
	    if ((propptr= fopen(optarg, "w")) == NULL) {
		perror(optarg);
                goto cleanup;
	    }
	    break;
	case 'L':
	  caCrlVersion = strtoul(optarg, 0, 0);
	  break;
	case 'l':
	  cpCrlVersion = strtoul(optarg, 0, 0);
	  break;
	default:
            printUsage();
            goto cleanup;
	}
    }

    if((argc-optind)!=5){
        fprintf(stderr,"\nmkCmd Error: too few required args (6)\n\n");
        printUsage();
        goto cleanup;
    }

    if((appInFile = fopen(argv[optind], "r"))==NULL){
        fprintf(stderr,"failed to open file %s\n",argv[optind]);
        goto cleanup;
    }

    if(certptr==NULL){
        sprintf(tmp_name,"%s/usr/host_data/%s", root_string, "cert.sys");
        certptr = fopen(tmp_name, "r");
        if(certptr == NULL){
            fprintf(stderr, "cert file (cert.sys) not found\n");
            exit(1);
        }
    }

    /* copy content desc from input file */

    memset(cmd.contentDesc, 0, BB_CMD_DESC_SIZE);
    if(contentDescFile)
        inBytes = fread(cmd.contentDesc, 1, BB_CMD_DESC_SIZE, contentDescFile);
    if((!IS_SYSAPP) && ((!contentDescFile) || (((OSBbLaunchMetaData *)(&cmd.contentDesc))->magic & 0x00FFFFFF) != ntohl(BB_METADATA_MAGIC))){
        fprintf(stderr,"contentDescFile is bogus (%08x)!!!\n",
                (int)((OSBbLaunchMetaData *)(&cmd.contentDesc))->magic);
        goto cleanup;
    }

    optind++;
    if(strlen(argv[optind])!=32){
        fprintf(stderr,"key string must contain 32 characters\n");
        goto cleanup;
    }
    strcpy(appAesKey,argv[optind]);

    optind++;
    if(strlen(argv[optind])!=32){
        fprintf(stderr,"key string must contain 32 characters\n");
        goto cleanup;
    }
    strcpy(appAesIv,argv[optind]);

    optind++;
    if((appOutFile = fopen(argv[optind], "w"))==NULL){
        fprintf(stderr,"failed to open file %s\n",argv[optind]);
        goto cleanup;
    }

    optind++;
    if((cmdOutFile = fopen(argv[optind], "w"))==NULL){
        fprintf(stderr,"failed to open file %s\n",argv[optind]);
        goto cleanup;
    }

    /* write content properties file */
    properties[0] = recrypt;
    if(IS_SYSAPP && (swRightsFlags==0 || hwRightsFlags==0)){
        /* override if obviously wrong */
        hwRightsFlags=PI_ACCESS_ERROR  | PI_ACCESS_IO  | PI_ACCESS_GPIO  | 
                      PI_ACCESS_BDMA   | PI_ACCESS_ATB | PI_ACCESS_FLASH | 
                      PI_ACCESS_BUFFER | BB_CMD_HWAR_USB_MASK; 
        swRightsFlags=0xffffffff;
    }
    properties[1] = hwRightsFlags;
    properties[2] = swRightsFlags;

    if(propptr){
        fwrite(properties,1,12,propptr);
        fclose(propptr);
    }
    
    /* zero, but not contentDesc since already set */
    memset(&cmd.head, 0, sizeof(BbContentMetaDataHead));

    /* commonIv default to random */
    for(i=0;i<sizeof(cmdAesIv);i+=4)
        *((u32 *)(commonIv+4)) = (u32)rand();

    if(strlen(cmdAesIv)>0){
        asciiToBin(cmdAesIv, 16, commonIv);
    }
    
    asciiToBin(appAesKey, 16, aesKey);
    
    asciiToBin(appAesIv, 16, aesIv);

    error = aesMakeKey(&key, AES_DIR_ENCRYPT, keyLen, (u8 *)aesKey);
    if (error != AES_TRUE) {
        fprintf(stderr,"Error creating aes key.\n");
        goto cleanup;
    }

    if ((error = aesCipherInit (&cipher, AES_MODE_CBC, (u8 *)aesIv)) != AES_TRUE) {
        fprintf(stderr,"Error initializing cipher.\n");
        goto cleanup;
    }

    SHA1Reset(&sha);

    contentBytes=0;
    while((inBytes = fread(ibuf, sizeof(ibuf[0]), BLK_SIZE, appInFile)) > 0) {
        contentBytes+=BLK_SIZE;
        if(inBytes<BLK_SIZE){
            memset(ibuf+inBytes,0,BLK_SIZE-inBytes);
        }
        SHA1Input(&sha,ibuf,BLK_SIZE);
        error = aesBlockEncrypt(&cipher, &key, ibuf,BLK_SIZE*8, obuf);
        if (error != (BLK_SIZE*8)) {
            fprintf(stderr,"Failed to encrypt block.\n");
            goto cleanup;
        }
        fwrite(obuf, sizeof(obuf[0]),BLK_SIZE, appOutFile);
    }

    /* set cmd hash */
    SHA1Result(&sha,(u8 *)hash);

    descflags = 0;
    if (IS_SYSAPP) {
	descflags = BB_CMD_DESC_COMMON_KEY;
    }


    generateUnsignedContentMetaDataHead(  caCrlVersion,
                                              cpCrlVersion,
                                              cid,
                                              contentBytes,
                                              descflags,
                                              commonIv,
                                              virageconstants,
                                              aesKey,
                                              hash,
                                              aesIv,
                                              properties,
                                              bbid,
                                              &cmd.head);

    /* encrypt portions that need it: handled in api */

    /* calculate sign */

/* compute keys  CP RSA 
 */

    memset(issuername, 0, sizeof issuername);
    prsa = RSA_new();
    if(cpKeyDataFile == NULL){
        sprintf(tmp_name,"%s/usr/host_data/%s", root_string, "cpbindata");
        if ((cpKeyDataFile = fopen(tmp_name,"r")) == NULL) {
            fprintf(stderr,"CP key data not found\n");
            return 1;
        }
        strcpy((char *)issuername, "Root-CPCA0000000e-CP0a0b0c0d");
    }
    /* for backward compatibility, readRsaDataNamed() will not alter
     * issuername arg if cpbindata file is used (doesn't hold name as
     * new .key file does).
     */
    readRsaDataNamed(cpKeyDataFile, prsa, (char *)issuername);
    memcpy(&cmd.head.issuer, issuername, sizeof issuername);

    size = RSA_size(prsa);
    verify = (unsigned char *) malloc(size);
    
    padded_data = (unsigned char *)malloc(size);
    
    /* compute hash before encrypting */
    SHA1Reset(&sha);
    if(IS_SYSAPP){
        SHA1Input(&sha,(u8 *)&cmd.head,BB_CMD_HEAD_SIGNED_BYTES);
    } else {
        SHA1Input(&sha,(u8 *)&cmd,BB_CMD_HEAD_SIGNED_BYTES + BB_CMD_DESC_SIZE);
    }
    SHA1Result(&sha, hash);
    RSA_padding_add_PKCS1_type_2(padded_data, size, hash, sizeof hash);

    size = RSA_private_encrypt(size, 
                      padded_data, signature, prsa, RSA_NO_PADDING);
    
    e_size = BN_bn2bin(prsa->e, e_string);
    n_size = BN_bn2bin(prsa->n, n_string);

#define get_word(x)	*(u32*)(x)
    certexponent = get_word(e_string);
    count = 0;
    for(i=0; i< n_size; i= i+4){
        certpublickey[count] = htonl(get_word(n_string + i));
        certsign[count] = htonl(get_word(signature + i));
        count++;
    }
    if(injectSigError){
        certsign[0] = ntohl(certsign[0]);
    }
    
#define VERIFY
#ifdef VERIFY
    size = RSA_size(prsa);
    memset(verify, 0, size);
    RSA_public_decrypt(size, signature, verify, prsa, RSA_NO_PADDING);
    bsl_rsa_verify(customResult, certsign, certpublickey, &certexponent, 2048);
    if(memcmp(customResult+size-sizeof hash, hash, sizeof hash) != 0 ||
       memcmp(verify+size-sizeof hash, hash, sizeof hash) != 0)
        printf("mkCmd: NOT OK FAIL test\n");
#endif
    
    /* copy the sign to its writeful place */
    memset(cmd.head.contentMetaDataSign, 0, sizeof cmd.head.contentMetaDataSign);
    for(i = 0; i < sizeof(BbRsaSig2048)/sizeof(u32); i++){
        cmd.head.contentMetaDataSign[i] = htonl(certsign[i]);
    }

    if(IS_SYSAPP) {
        if (fwrite((void *)&cmd.head, 1, sizeof(BbContentMetaDataHead), 
                   cmdOutFile) < 0) {
            perror("fwrite");
            goto cleanup;
        }
    } else {
        if (fwrite((void *)&cmd, 1, sizeof(BbContentMetaData), 
                   cmdOutFile) < 0) {
            perror("fwrite");
            goto cleanup;
        }
    }

    /* create sysapp "ticket" bundle */
    if(IS_SYSAPP){
        int numCerts;
        BbRsaCert *cert;
        fread(&numCerts,4,1,certptr);
        numCerts = ntohl(numCerts);
        buf=malloc(numCerts*sizeof(BbRsaCert));
        fread(buf,1,numCerts*sizeof(BbRsaCert),certptr);
        fclose(certptr);
        for(i=0, cert=(BbRsaCert *)buf;
            i<numCerts && strncmp(cert->certId.name.server,
                                  &cmd.head.issuer[18],10);
            i++, cert++){}
        if(i==numCerts){
            perror("cannot find signer cert for sysapp bundle\n");
            goto cleanup;
        }
        if (fwrite((void *)cert,1,sizeof(BbRsaCert),cmdOutFile) < 0){
            perror("fwrite");
            goto cleanup;
        }
        for(i=0, cert=(BbRsaCert *)buf;
            i<numCerts && strncmp(cert->certId.name.server,
                                  &cmd.head.issuer[5],12);
            i++, cert++){}
        if(i==numCerts){
            perror("cannot find ca cert for sysapp bundle\n");
            goto cleanup;
        }
        if (fwrite((void *)cert,1,sizeof(BbRsaCert),cmdOutFile) < 0){
            perror("fwrite");
            goto cleanup;
        }
        free(buf);
    }

    return 0;

 cleanup:
    if(cmdOutFile)
        fclose(cmdOutFile);
    if(appInFile)
        fclose(appInFile);
    if(appOutFile)
        fclose(appOutFile);
    if(contentDescFile)
        fclose(contentDescFile);
    if(prsa) free(prsa);
    if(viragefileptr) fclose(viragefileptr);
    if(verify) free(verify);
    if(padded_data) free(padded_data);
    if(buf) free(buf);
    return 1;
}