testtick.c 9.06 KB
#include <PR/bcp.h>
#include <PR/R4300.h>
#include <PR/bbsim.h>
#include <PR/bbskapi.h>

#include <PR/os.h>
#include <PR/os_bb.h>
#include <PR/os_bbfs.h>
#include <PR/os_bbatb.h>
#include <PR/os_bbexec.h>
#include <PR/ramrom.h>

#include <PR/os_bbsa.h>
#include <libfb.h>
#include <bb_nn.h>
#include <sha1.h>
#include "testtick.h"

#include "nu64sys.h"
#include "graph.h"

#define ALIGN_DCACHE __attribute__((aligned(DCACHE_LINESIZE)))
#define printstr fbPrintf

static u32 gMiSecModeRegEntryVal;
static char gDispStr[1024];
static int gTicketIndex;
OSBbSaTickets      gTickets __attribute__((aligned(16)));
OSBbSaGameMetaData gGameMeta[32];
extern u32  __osBbHackFlags;


/*
 * debug print support
 */

#undef PRINTF

#ifdef DEBUG
#define	PRINTF	osSyncPrintf
#else
#define	PRINTF(format, args...)
#endif

#define fbhBlue         GPACK_RGBA5551(0,0,80,1)
#define fbhGreen        GPACK_RGBA5551(0,80,0,1)
#define fbhRed          GPACK_RGBA5551(80,0,0,1)
#define fbhYellow       GPACK_RGBA5551(80,80,0,1)
#define fbhMagenta      GPACK_RGBA5551(80,0,80,1)
#define fbhCyan         GPACK_RGBA5551(0,80,80,1)

#define fbLemonChiffon          GPACK_RGBA5551(255,250,205,1)
#define fbLightSlateBlue        GPACK_RGBA5551(132,112,255,1)
#define fbLightPink1            GPACK_RGBA5551(255,174,185,1)
#define fbThistle2              GPACK_RGBA5551(238,210,238,1)
#define fbSeaGreen4             GPACK_RGBA5551(105,139,105,1)
#define fbTomato1               GPACK_RGBA5551(255,99,71,1)
#define fbTurquoise2            GPACK_RGBA5551(0,229,238,1)
#define fbSienna4               GPACK_RGBA5551(139,71,38,1)


/*
 * Thread and stack structures
 */

char   bootStack[STACKSIZE] __attribute__ ((aligned (8)));

static OSThread idleThread;
static char     idleThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

static OSThread mainThread;
static char     mainThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

/* 
 * FS specific definitions
 */

static void	idleproc(char *);
static void	mainproc(char *);
static OSBbFs   gFs; /* too big to plop on the stack */

/* XXX: hard-coded size requires more consideration */
#define BB_SYSAPP_NUM_DIR_ENTRIES 256
static OSBbDirEnt gFsDirs[BB_SYSAPP_NUM_DIR_ENTRIES];

static const char gTicketFname[] = "ticket.sys";

#define BB_SYSAPP_CERT_BUF_SIZE (16*1024*4)
static u8 gCertBuf[BB_SYSAPP_CERT_BUF_SIZE] ALIGN_DCACHE;

#define BB_SYSAPP_RL_BUF_SIZE (16*1024*4)
static u8 gRlBuf[BB_SYSAPP_RL_BUF_SIZE] ALIGN_DCACHE;


#define DMA_QUEUE_SIZE	200

static OSMesg           PiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      PiMessageQ;

static OSMesg           SiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      SiMessageQ;


/*
 * simple graphics
 */

static OSMesgQueue      retraceMessageQ;
static OSMesg           dummyMessage, retraceMessageBuf;
static u16 cfb[320*240] __attribute__((aligned(64)));

/*
 * controller
 */
static OSMesgQueue      contMessageQ;
OSContStatus statusData[MAXCONTROLLERS];
OSContPad controllerData[MAXCONTROLLERS];
static int no_controller = 1;

#define EXTERN_LIMIT 2
static void
initController(void)
{
    int i, c = 0;
    u8 pattern;

    if (__osBbIsBb<2)
        __osBbHackFlags = 1;
    else
        __osBbHackFlags = 0;

    osCreateMesgQueue(&contMessageQ, &dummyMessage, 1);
    osSetEventMesg(OS_EVENT_SI, &contMessageQ, (OSMesg) 0);

    osContInit(&contMessageQ, &pattern, &statusData[0]);

    for (i = 0; i < MAXCONTROLLERS; i++) {
        if ((pattern & (1 << i)) &&
            !(statusData[i].errno & CONT_NO_RESPONSE_ERROR)) {
            ++c;
            no_controller = 0;
        }
    }
}


void outputCid()
{
    sprintf(gDispStr,"CID: %08x",
            (unsigned int)(gTickets.ticket[gTicketIndex].cmd.head.id));
    printstr(fbWhite, 3, 6, gDispStr);
    osWritebackDCacheAll();
}


static void
delay(void) {
    int k;
    for(k = 0; k < 1000000; k++)
	;
}

void  __osBbVideoPllInit(u32);
void boot(u32 miSecModeRegVal)
{
    gMiSecModeRegEntryVal = miSecModeRegVal;

    /* Init the video PLL */
    __osBbVideoPllInit(OS_TV_NTSC);

    osInitialize();

    osCreateThread(&idleThread, 1, (void(*)(void *))idleproc, (void *)0,
                   idleThreadStack+STACKSIZE, 8);
    osStartThread(&idleThread);
}


static void
idleproc(char *argv)		/* priority 8 */
{
    osCreateViManager(OS_PRIORITY_VIMGR);
    fbInit(FB_LOW_RES);

#ifdef DEBUG
    /* should allow usb printing */
    osBbUsbInit();
#endif

    /*
     * Start PI Mgr for access to cartridge - start before the debugger
     */
    osCreatePiManager((OSPri) OS_PRIORITY_PIMGR, &PiMessageQ, PiMessages,
            DMA_QUEUE_SIZE);

    osCreateMesgQueue(&SiMessageQ, SiMessages, DMA_QUEUE_SIZE);
    osSetEventMesg(OS_EVENT_SI, &SiMessageQ, (OSMesg)DMA_QUEUE_SIZE);

    /*
     * The main thread's priority must be the same or lower than the original
     * idle's thread priority. This allows the idle thread to change its
     * priority to 0 before the main thread starts execution.
     */
    osCreateThread(&mainThread, 3, (void(*)(void *))mainproc, argv,
           mainThreadStack+STACKSIZE/8, (OSPri)7);
    osStartThread(&mainThread);

    osSetThreadPri(0, OS_PRIORITY_IDLE);

    for(;;){}
}


static int memcmp(const void *s1, const void *s2, size_t n)
{
    const u8* a = s1, * b = s2;
    u8 a1, b1;
    while (n-- > 0) {
	if ((a1 = *a++) == (b1 = *b++)) continue;
	return a1 - b1;
    }
    return 0;
}

int osBbSaVerifyTickets(OSBbSaTickets *ticketset){
  BbTicketBundle ticketBundle;    
  BbAppLaunchCrls appRls;
  SHA1Context sha;
  u32 compareStart = 0;
  BbShaHash hash_data;
  BbRsaPublicKey2048 authpublickey;
  BbRsaExponent authexponent;
  unsigned char  computedSig[sizeof(BbRsaPublicKey4096)];
  int i;
  

/* zero public key and exponent until an authentic one is found */
  bzero((u8 *)authpublickey, sizeof(BbRsaPublicKey2048));
  bzero((u8 *)&authexponent, sizeof(BbRsaExponent));
  for(i=0; i< ticketset->numTickets; i++){ 
    if(BB_SYSAPP_PASS != osBbSaBundleTicket(&(ticketset->ticket[i]), 
					    &ticketBundle,
					    &appRls,
					    gCertBuf, sizeof(gCertBuf),
					    gRlBuf, sizeof(gRlBuf))){
      
      return BB_SYSAPP_FAIL;
      }
      /* compute hash */
    SHA1Reset(&sha);
    SHA1Input(&sha, (u8 *) ticketBundle.ticket, 
	      (sizeof(BbTicket) - sizeof(BbRsaSig2048)));
    SHA1Result(&sha, (u8 *) hash_data);
     /* verify ticket */
    if(i ==0){
	/* call sk function first time */
      if(skVerifyHash(hash_data,
		      (BbGenericSig *)&(ticketBundle.ticket->head).ticketSign,
		      ticketBundle.ticketChain, 
		      &appRls) == SK_API_SUCCESS){
	/* if success, get authenticated public key and exponent */
	memcpy(authpublickey, ((BbRsaCert *)ticketBundle.ticketChain[0])->publicKey,sizeof(BbRsaPublicKey2048));
	memcpy(&authexponent, &(((BbRsaCert *)ticketBundle.ticketChain[0])->exponent), sizeof(BbRsaExponent));
      }
      else{
	return BB_SYSAPP_FAIL;
      }
    }
    /* other tickets */
    else{
      /* verify directly from libcrypto to avoid cert checks again*/
      bsl_rsa_verify(computedSig, 
		     (u32 *)(BbGenericSig *)&(ticketBundle.ticket->head).ticketSign, 
		     authpublickey, 
		     &authexponent, 
		     2048);
      compareStart = sizeof(BbRsaPublicKey2048) - sizeof(BbShaHash);
      if (memcmp(hash_data, computedSig+compareStart, sizeof(BbShaHash))!=0){
	return BB_SYSAPP_FAIL;
      }
    }
  }
  return BB_SYSAPP_PASS;
}

void mainproc(char *argv)
{
    
    s32 fsret;
    char tmp[16];
  
    /* setup text output to screen */
    char outstring[512];
    osCreateMesgQueue(&retraceMessageQ, &retraceMessageBuf, 1);
    osViSetEvent(&retraceMessageQ, dummyMessage, 1);
    osViBlack(1);
    osViSwapBuffer(cfb);
    fbSetBg(fbBlack);
    fbClear();
    osViBlack(0);
    osWritebackDCacheAll();
    osViSwapBuffer(cfb);
    fbClear();
    initController();

    printstr(fbWhite, 3, 2, "Test Ticket App");
    osWritebackDCacheAll();

    if(osBbFInit(&gFs)<0){
        goto exit;
    }

    /* power-down */
    /* check for rev 1.1 version of BCP */
    if (IO_READ(PI_GPIO_REG) & PI_ID_BOARD_REV_MASK){
        if( gMiSecModeRegEntryVal & MI_SEC_MODE_BUT_TRAP){
            osBbSaveState(tmp);
            printstr(fbWhite, 3, 12, "POWER DOWN");
            osWritebackDCacheAll();
            delay();
            osBbPowerOff();
            return;
        }
    }else{
        osBbSaveState(tmp);
    }
    
    fsret = osBbFReadDir(gFsDirs, BB_SYSAPP_NUM_DIR_ENTRIES);
    if(fsret<0){
        goto exit;
    }

    osBbSaMetaGetTickets(&gTickets);

    gTicketIndex = 0;
    outputCid();

    if( osBbSaVerifyTickets(&gTickets) == BB_SYSAPP_PASS){
#ifdef DEBUG
      PRINTF("TICKET FILE CHECK PASS \n");
#endif
      sprintf(outstring, "TICKET FILE CHECK PASS");
      printstr(white, 3, 8, outstring);
      osWritebackDCacheAll();
    }
    else{
#ifdef DEBUG
      PRINTF("TICKET FILE CHECK FAIL \n");
#endif
      sprintf(outstring, "TICKET FILE CHECK FAIL");
      printstr(white, 3, 9, outstring);
      osWritebackDCacheAll();
    }
    for(;;){
    delay();
    }

 exit:
    PRINTF("\nAPP FINISHED\n");
    /* power off (cannot do this since not in secure mode) */
    printstr(fbWhite, 3, 12, "Test Done");
    osWritebackDCacheAll();
    delay();
    osBbPowerOff();
    return;
}