Example #1
0
def solidCompressXci(filePath, compressionLevel, outputDir, threads,
                     stusReport, id, pleaseNoPrint):
    filePath = filePath.resolve()
    container = factory(filePath)
    container.open(str(filePath), 'rb')
    secureIn = container.hfs0['secure']
    xczPath = outputDir.joinpath(filePath.stem + '.xcz')

    Print.info(
        'Solid compressing (level {0}) {1} -> {2}'.format(
            compressionLevel, filePath, xczPath), pleaseNoPrint)

    try:
        with Xci.XciStream(
                str(xczPath), originalXciPath=filePath
        ) as xci:  # need filepath to copy XCI container settings
            with Hfs0.Hfs0Stream(xci.hfs0.add('secure', 0, pleaseNoPrint),
                                 xci.f.tell()) as secureOut:
                processContainer(secureIn, secureOut, compressionLevel,
                                 threads, stusReport, id, pleaseNoPrint)

            xci.hfs0.resize('secure', secureOut.actualSize)
    except BaseException as ex:
        if not ex is KeyboardInterrupt:
            Print.error(format_exc())
        if xczPath.is_file():
            xczPath.unlink()

    container.close()
    return xczPath
Example #2
0
def __decompressXcz(filePath, outputDir, write, raiseVerificationException,
                    statusReportInfo, pleaseNoPrint):
    fileHashes = FileExistingChecks.ExtractHashes(filePath)
    container = factory(filePath)
    container.open(filePath, 'rb')
    secureIn = container.hfs0['secure']

    if write:
        filename = changeExtension(filePath, '.xci')
        outPath = filename if outputDir == None else str(
            Path(outputDir).joinpath(filename))
        Print.info('Decompressing %s -> %s' % (filePath, outPath),
                   pleaseNoPrint)
        with Xci.XciStream(
                outPath, originalXciPath=filePath
        ) as xci:  # need filepath to copy XCI container settings
            with Hfs0.Hfs0Stream(xci.hfs0.add('secure', 0, pleaseNoPrint),
                                 xci.f.tell()) as secureOut:
                __decompressContainer(secureIn, secureOut, fileHashes, write,
                                      raiseVerificationException,
                                      statusReportInfo, pleaseNoPrint)
                xci.hfs0.resize('secure', secureOut.actualSize)
    else:
        __decompressContainer(secureIn, None, fileHashes, write,
                              raiseVerificationException, statusReportInfo,
                              pleaseNoPrint)

    container.close()
Example #3
0
def check_xci_certs(ifolder, tfile, tfile2):
    from listmanager import folder_to_list, striplines, read_lines_to_list
    from Fs import Xci
    import os
    if not os.path.exists(tfile):
        xci_files = folder_to_list(ifolder, ['xci'])
        with open(tfile, "w", encoding='utf8') as t:
            for file in xci_files:
                t.write(file + '\n')
    else:
        xci_files = read_lines_to_list(tfile, all=True)
    counter = len(xci_files)
    for file in xci_files:
        try:
            xci = Xci(file)
            if not xci.gamecardCert.Cert_is_fake:
                print(f"{file} has personalized certificate")
                with open(tfile2, "a", encoding='utf8') as t:
                    t.write(file + '\n')
            else:
                print(f"{file} has a wiped certificate")
            xci.close()
            counter -= 1
            striplines(tfile, 1, True)
        except:
            try:
                with open(tfile2, "a", encoding='utf8') as t:
                    t.write("Error:" + file + '\n')
            except:
                pass
            counter -= 1
            striplines(tfile, 1, True)
    try:
        os.remove(tfile)
    except:
        pass
Example #4
0
def gen_xci_parts(filepath,cachefolder=None,keepupd=False,id_target=False,keypatch=False,export_type='csv'):
	if not os.path.exists(cachefolder):
		os.makedirs(cachefolder)
	else:
		for f in os.listdir(cachefolder):
			fp = os.path.join(cachefolder, f)
			try:
				shutil.rmtree(fp)
			except OSError:
				os.remove(fp)
	files_list=sq_tools.ret_xci_offsets(filepath)
	files=list();filesizes=list()
	fplist=list()
	for k in range(len(files_list)):
		entry=files_list[k]
		fplist.append(entry[0])
	for i in range(len(files_list)):
		entry=files_list[i]
		cnmtfile=entry[0]
		if cnmtfile.endswith('.cnmt.nca'):
			f=squirrelXCI(filepath)
			titleid,titleversion,base_ID,keygeneration,rightsId,RSV,RGV,ctype,metasdkversion,exesdkversion,hasHtmlManual,Installedsize,DeltaSize,ncadata=f.get_data_from_cnmt(cnmtfile)
			f.flush()
			f.close()
			for j in range(len(ncadata)):
				row=ncadata[j]
				# print(row)
				if row['NCAtype']!='Meta' and row['NCAtype']!='Program':
					test1=str(row['NcaId'])+'.nca';test2=str(row['NcaId'])+'.ncz'
					if test1 in fplist or test2 in fplist:
						# print(str(row['NcaId'])+'.nca')
						files.append(str(row['NcaId'])+'.nca')
						filesizes.append(int(row['Size']))					
				elif row['NCAtype']=='Meta':
					# print(str(row['NcaId'])+'.cnmt.nca')
					files.append(str(row['NcaId'])+'.cnmt.nca')
					filesizes.append(int(row['Size']))	
			for j in range(len(ncadata)):
				row=ncadata[j]
				# print(row)
				if row['NCAtype']=='Program':
					test1=str(row['NcaId'])+'.nca';test2=str(row['NcaId'])+'.ncz'
					if test1 in fplist or test2 in fplist:
						# print(str(row['NcaId'])+'.nca')
						files.append(str(row['NcaId'])+'.nca')
						filesizes.append(int(row['Size']))				
	f.flush()
	f.close()						
	outheader = sq_tools.gen_nsp_header(files,filesizes)	
	properheadsize=len(outheader)
	# print(properheadsize)
	# print(bucketsize)
	i=0;sum=properheadsize;
	for file in files:
		# print(file)
		# print(filesizes[i])
		if i<(len(files)-1):
			sum+=filesizes[i]
		i+=1
	# print(sum)
	# print(sum/bucketsize)
	multiplier=math.ceil(sum/bucketsize)
	# print(multiplier)
	remainder = bucketsize*multiplier - sum
	# print(bucketsize*multiplier)
	xci=squirrelXCI(filepath)
	outfile=os.path.join(cachefolder, "0")
	written=0;
	outf = open(outfile, 'w+b')		
	outf.write(outheader)	
	written+=len(outheader)
	for fi in files:
		for nspF in xci.hfs0:
			if str(nspF._path)=="secure":
				for nca in nspF:	
					if nca._path==fi:
						crypto1=nca.header.getCryptoType()
						crypto2=nca.header.getCryptoType2()	
						if crypto2>crypto1:
							masterKeyRev=crypto2
						if crypto2<=crypto1:	
							masterKeyRev=crypto1						
						crypto = aes128.AESECB(Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev), nca.header.keyIndex))
						hcrypto = aes128.AESXTS(uhx(Keys.get('header_key')))	
						gc_flag='00'*0x01					
						crypto1=nca.header.getCryptoType()
						crypto2=nca.header.getCryptoType2()					
						if nca.header.getRightsId() != 0:				
							nca.rewind()	
							encKeyBlock = crypto.encrypt(titleKeyDec * 4)
							if str(keypatch) != "False":
								if keypatch < nca.header.getCryptoType2():
									encKeyBlock,crypto1,crypto2=squirrelXCI.get_new_cryptoblock(nca, keypatch,encKeyBlock,t)	
						if nca.header.getRightsId() == 0:
							nca.rewind()				
							encKeyBlock = nca.header.getKeyBlock()	
							if str(keypatch) != "False":
								if keypatch < nca.header.getCryptoType2():
									encKeyBlock,crypto1,crypto2=squirrelXCI.get_new_cryptoblock(nca, keypatch,encKeyBlock,t)					
						nca.rewind()					
						i=0				
						newheader=xci.get_newheader(nca,encKeyBlock,crypto1,crypto2,hcrypto,gc_flag)		
						outf.write(newheader)
						written+=len(newheader)
						nca.seek(0xC00)	
						if (str(nca.header.contentType) != 'Content.PROGRAM'):
							data=nca.read()	
							nca.close()
							outf.write(data)
							written+=len(data)
						else:
							remainder = bucketsize*multiplier - written
							data=nca.read(remainder)
							nca.close()
							outf.write(data)
							written+=len(data)						
						break					
					else:pass
	outf.close()		
	if export_type=='json':
		files_json=os.path.join(cachefolder, "files.json")	
		d={}
		d['0']={"step": 0,
		  "filepath":outfile ,
		  "size":( bucketsize*multiplier) ,
		  "targetsize":( bucketsize*multiplier) ,
		  "off1":0,
		  "off2":( bucketsize*multiplier)
		}
		for j in files_list:
			if j[0]==files[-1]:
				off1=j[1]
				off2=j[2]
				targetsize=j[3]
		d['1']={"step": 1,
		  "filepath":filepath ,
		  "size":( os.path.getsize(filepath)) ,
		  "targetsize":targetsize,
		  "off1":off1,
		  "off2":off2
		}	
		app_json = json.dumps(d, indent=1)
		with open(files_json, 'w') as json_file:
		  json_file.write(app_json)			
		# print(os.path.getsize(filepath))	
	else:
		for j in files_list:
			if j[0]==files[-1]:
				off1=j[1]
				off2=j[2]
				targetsize=j[3]	
		tfile=os.path.join(cachefolder, "files.csv")
		i=0;
		with open(tfile,'w') as csvfile:
			if i==0:
				csvfile.write("{}|{}|{}|{}|{}|{}\n".format("step","filepath","size","targetsize","off1","off2"))
				i+=1
			if i==1:	
				csvfile.write("{}|{}|{}|{}|{}|{}\n".format(0,outfile,( bucketsize*multiplier),( bucketsize*multiplier),0,( bucketsize*multiplier)))		
				i+=1				
			if i==2:	
				csvfile.write("{}|{}|{}|{}|{}|{}".format(1,filepath,( os.path.getsize(filepath)),targetsize,off1,off2))		
				i+=1			
def decompress_xcz(input,output,buffer = 65536):
	f = Xci(input)
	f.decompress_direct(output,buffer)
	f.flush()
	f.close()	
Example #6
0
def gen_xci_parts_spec1(filepath,
                        target_cnmt=None,
                        cachefolder=None,
                        keypatch=False):
    if keypatch != False:
        try:
            keypatch = int(keypatch)
        except:
            keypatch = False
    if cachefolder == None:
        cachefolder = os.path.join(ztools_dir, '_mtp_cache_')
    if not os.path.exists(cachefolder):
        os.makedirs(cachefolder)
    else:
        for f in os.listdir(cachefolder):
            fp = os.path.join(cachefolder, f)
            try:
                shutil.rmtree(fp)
            except OSError:
                os.remove(fp)
    files_list = sq_tools.ret_xci_offsets(filepath)
    files = list()
    filesizes = list()
    fplist = list()
    for k in range(len(files_list)):
        entry = files_list[k]
        fplist.append(entry[0])
    if target_cnmt == None:
        for i in range(len(files_list)):
            entry = files_list[i]
            cnmtfile = entry[0]
            if cnmtfile.endswith('.cnmt.nca'):
                target_cnmt = cnmtfile
                break
    for i in range(len(files_list)):
        entry = files_list[i]
        cnmtfile = entry[0]
        if cnmtfile.endswith('.cnmt.nca') and target_cnmt == cnmtfile:
            f = squirrelXCI(filepath)
            titleid, titleversion, base_ID, keygeneration, rightsId, RSV, RGV, ctype, metasdkversion, exesdkversion, hasHtmlManual, Installedsize, DeltaSize, ncadata = f.get_data_from_cnmt(
                cnmtfile)
            f.flush()
            f.close()
            for j in range(len(ncadata)):
                row = ncadata[j]
                # print(row)
                if row['NCAtype'] != 'Meta' and row['NCAtype'] != 'Program':
                    test1 = str(row['NcaId']) + '.nca'
                    test2 = str(row['NcaId']) + '.ncz'
                    if test1 in fplist:
                        files.append(str(row['NcaId']) + '.nca')
                        filesizes.append(int(row['Size']))
                    elif test2 in fplist:
                        files.append(str(row['NcaId']) + '.ncz')
                        for k in range(len(files_list)):
                            entry = files_list[k]
                            if entry[0] == test2:
                                filesizes.append(int(entry[3]))
                                break
            for j in range(len(ncadata)):
                row = ncadata[j]
                if row['NCAtype'] == 'Meta':
                    # print(str(row['NcaId'])+'.cnmt.nca')
                    files.append(str(row['NcaId']) + '.cnmt.nca')
                    filesizes.append(int(row['Size']))
            for j in range(len(ncadata)):
                row = ncadata[j]
                # print(row)
                if row['NCAtype'] == 'Program':
                    test1 = str(row['NcaId']) + '.nca'
                    test2 = str(row['NcaId']) + '.ncz'
                    if test1 in fplist:
                        files.append(str(row['NcaId']) + '.nca')
                        filesizes.append(int(row['Size']))
                    elif test2 in fplist:
                        files.append(str(row['NcaId']) + '.ncz')
                        for k in range(len(files_list)):
                            entry = files_list[k]
                            if entry[0] == test2:
                                filesizes.append(int(entry[3]))
                                break
            break
    f.flush()
    f.close()
    outheader = sq_tools.gen_nsp_header(files, filesizes)
    properheadsize = len(outheader)
    # print(properheadsize)
    # print(bucketsize)
    i = 0
    sum = properheadsize
    xci = squirrelXCI(filepath)
    outfile = os.path.join(cachefolder, "0")
    outf = open(outfile, 'w+b')
    outf.write(outheader)
    written = 0
    for fi in files:
        for nspF in xci.hfs0:
            if str(nspF._path) == "secure":
                for nca in nspF:
                    if nca._path == fi:
                        nca = Nca(nca)
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if crypto2 > crypto1:
                            masterKeyRev = crypto2
                        if crypto2 <= crypto1:
                            masterKeyRev = crypto1
                        crypto = aes128.AESECB(
                            Keys.keyAreaKey(
                                Keys.getMasterKeyIndex(masterKeyRev),
                                nca.header.keyIndex))
                        hcrypto = aes128.AESXTS(uhx(Keys.get('header_key')))
                        gc_flag = '00' * 0x01
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if nca.header.getRightsId() != 0:
                            nca.rewind()
                            if crypto2 > crypto1:
                                masterKeyRev = crypto2
                            if crypto2 <= crypto1:
                                masterKeyRev = crypto1
                            from mtp_tools import get_nca_ticket
                            check, titleKey = get_nca_ticket(filepath, fi)
                            if check == False:
                                sys.exit("Can't verify titleckey")
                            titleKeyDec = Keys.decryptTitleKey(
                                titleKey,
                                Keys.getMasterKeyIndex(int(masterKeyRev)))
                            encKeyBlock = crypto.encrypt(titleKeyDec * 4)
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                        squirrelXCI, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        if nca.header.getRightsId() == 0:
                            nca.rewind()
                            encKeyBlock = nca.header.getKeyBlock()
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                        squirrelXCI, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        nca.rewind()
                        i = 0
                        newheader = xci.get_newheader(nca, encKeyBlock,
                                                      crypto1, crypto2,
                                                      hcrypto, gc_flag)
                        outf.write(newheader)
                        written += len(newheader)
                        nca.seek(0xC00)
                        break
                    else:
                        pass
    xci.flush()
    xci.close()
    outf.flush()
    outf.close()
    tfile = os.path.join(cachefolder, "files.csv")
    with open(tfile, 'w') as csvfile:
        csvfile.write("{}|{}|{}|{}|{}|{}\n".format("step", "filepath", "size",
                                                   "targetsize", "off1",
                                                   "off2"))
        csvfile.write("{}|{}|{}|{}|{}|{}\n".format(0, outfile,
                                                   properheadsize + written,
                                                   properheadsize, 0,
                                                   properheadsize))
        k = 0
        l = 0
        for fi in files:
            for j in files_list:
                if j[0] == fi:
                    csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                        k + 1, outfile, properheadsize + written, 0xC00,
                        (properheadsize + l * 0xC00),
                        (properheadsize + (l * 0xC00) + 0xC00)))
                    off1 = j[1] + 0xC00
                    off2 = j[2]
                    targetsize = j[3] - 0xC00
                    csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                        k + 2, filepath, (os.path.getsize(filepath)),
                        targetsize, off1, off2))
                    break
            k += 2
            l += 1
    nspname = "test.nsp"
    try:
        g = os.path.basename(filepath)
        g0 = [pos for pos, char in enumerate(g) if char == '[']
        g0 = (g[0:g0[0]]).strip()
        nspname = f"{g0} [{titleid}] [v{titleversion}] [{ctype}].nsp"
    except:
        pass
    return nspname
Example #7
0
def gen_xci_parts_spec0(filepath,
                        target_cnmt=None,
                        cachefolder=None,
                        keypatch=False,
                        export_type='csv'):
    if cachefolder == None:
        cachefolder = os.path.join(ztools_dir, '_mtp_cache_')
    if not os.path.exists(cachefolder):
        os.makedirs(cachefolder)
    else:
        for f in os.listdir(cachefolder):
            fp = os.path.join(cachefolder, f)
            try:
                shutil.rmtree(fp)
            except OSError:
                os.remove(fp)
    program_name = None
    files_list = sq_tools.ret_xci_offsets(filepath)
    files = list()
    filesizes = list()
    fplist = list()
    for k in range(len(files_list)):
        entry = files_list[k]
        fplist.append(entry[0])
    if target_cnmt == None:
        for i in range(len(files_list)):
            entry = files_list[i]
            cnmtfile = entry[0]
            if cnmtfile.endswith('.cnmt.nca'):
                target_cnmt = cnmtfile
                break
    for i in range(len(files_list)):
        entry = files_list[i]
        cnmtfile = entry[0]
        if cnmtfile.endswith('.cnmt.nca') and target_cnmt == cnmtfile:
            f = squirrelXCI(filepath)
            titleid, titleversion, base_ID, keygeneration, rightsId, RSV, RGV, ctype, metasdkversion, exesdkversion, hasHtmlManual, Installedsize, DeltaSize, ncadata = f.get_data_from_cnmt(
                cnmtfile)
            f.flush()
            f.close()
            for j in range(len(ncadata)):
                row = ncadata[j]
                # print(row)
                if row['NCAtype'] != 'Meta' and row['NCAtype'] != 'Program':
                    test1 = str(row['NcaId']) + '.nca'
                    test2 = str(row['NcaId']) + '.ncz'
                    if test1 in fplist or test2 in fplist:
                        # print(str(row['NcaId'])+'.nca')
                        if test1 in fplist:
                            files.append(str(row['NcaId']) + '.nca')
                            filesizes.append(int(row['Size']))
                        elif test2 in fplist:
                            files.append(str(row['NcaId']) + '.ncz')
                            for k in range(len(files_list)):
                                entry = files_list[k]
                                if entry[0] == test2:
                                    filesizes.append(int(entry[3]))
                                    break
            for j in range(len(ncadata)):
                row = ncadata[j]
                if row['NCAtype'] == 'Meta':
                    # print(str(row['NcaId'])+'.cnmt.nca')
                    files.append(str(row['NcaId']) + '.cnmt.nca')
                    filesizes.append(int(row['Size']))
            for j in range(len(ncadata)):
                row = ncadata[j]
                # print(row)
                if row['NCAtype'] == 'Program':
                    test1 = str(row['NcaId']) + '.nca'
                    test2 = str(row['NcaId']) + '.ncz'
                    if test1 in fplist or test2 in fplist:
                        # print(str(row['NcaId'])+'.nca')
                        if test1 in fplist:
                            files.append(str(row['NcaId']) + '.nca')
                            filesizes.append(int(row['Size']))
                        elif test2 in fplist:
                            files.append(str(row['NcaId']) + '.ncz')
                            for k in range(len(files_list)):
                                entry = files_list[k]
                                if entry[0] == test2:
                                    filesizes.append(int(entry[3]))
                                    break
            break
    f.flush()
    f.close()
    outheader = sq_tools.gen_nsp_header(files, filesizes)
    properheadsize = len(outheader)
    # print(properheadsize)
    # print(bucketsize)
    i = 0
    sum = properheadsize
    for file in files:
        # print(file)
        # print(filesizes[i])
        if i < (len(files) - 1):
            sum += filesizes[i]
        i += 1
    # print(sum)
    # print(sum/bucketsize)
    multiplier = math.ceil(sum / bucketsize)
    # print(multiplier)
    remainder = bucketsize * multiplier - sum
    # print(bucketsize*multiplier)
    xci = squirrelXCI(filepath)
    outfile = os.path.join(cachefolder, "0")
    written = 0
    outf = open(outfile, 'w+b')
    outf.write(outheader)
    written += len(outheader)
    movoffset = 0
    for fi in files:
        for nspF in xci.hfs0:
            if str(nspF._path) == "secure":
                for nca in nspF:
                    if nca._path == fi:
                        nca = Nca(nca)
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if crypto2 > crypto1:
                            masterKeyRev = crypto2
                        if crypto2 <= crypto1:
                            masterKeyRev = crypto1
                        crypto = aes128.AESECB(
                            Keys.keyAreaKey(
                                Keys.getMasterKeyIndex(masterKeyRev),
                                nca.header.keyIndex))
                        hcrypto = aes128.AESXTS(uhx(Keys.get('header_key')))
                        gc_flag = '00' * 0x01
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if nca.header.getRightsId() != 0:
                            nca.rewind()
                            if crypto2 > crypto1:
                                masterKeyRev = crypto2
                            if crypto2 <= crypto1:
                                masterKeyRev = crypto1
                            from mtp_tools import get_nca_ticket
                            check, titleKey = get_nca_ticket(filepath, fi)
                            if check == False:
                                sys.exit("Can't verify titleckey")
                            titleKeyDec = Keys.decryptTitleKey(
                                titleKey,
                                Keys.getMasterKeyIndex(int(masterKeyRev)))
                            encKeyBlock = crypto.encrypt(titleKeyDec * 4)
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                        squirrelXCI, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        if nca.header.getRightsId() == 0:
                            nca.rewind()
                            encKeyBlock = nca.header.getKeyBlock()
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                        squirrelXCI, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        nca.rewind()
                        i = 0
                        newheader = xci.get_newheader(nca, encKeyBlock,
                                                      crypto1, crypto2,
                                                      hcrypto, gc_flag)
                        outf.write(newheader)
                        written += len(newheader)
                        nca.seek(0xC00)
                        movoffset += 0xC00
                        if (str(nca.header.contentType) != 'Content.PROGRAM'):
                            data = nca.read()
                            nca.close()
                            outf.write(data)
                            written += len(data)
                        break
                    else:
                        pass
    xci.flush()
    xci.close()
    outf.close()
    if export_type == 'json':
        files_json = os.path.join(cachefolder, "files.json")
        d = {}
        d['0'] = {
            "step": 0,
            "filepath": outfile,
            "size": (written),
            "targetsize": (written),
            "off1": 0,
            "off2": (written)
        }
        for j in files_list:
            if j[0] == files[-1]:
                off1 = j[1] + 0xC00
                off2 = j[2]
                targetsize = j[3] - 0xC00
        d['1'] = {
            "step": 1,
            "filepath": filepath,
            "size": (os.path.getsize(filepath)),
            "targetsize": targetsize,
            "off1": off1,
            "off2": off2
        }
        app_json = json.dumps(d, indent=1)
        with open(files_json, 'w') as json_file:
            json_file.write(app_json)
        # print(os.path.getsize(filepath))
    else:
        for j in files_list:
            if j[0] == files[-1]:
                off1 = j[1] + 0xC00
                off2 = j[2]
                targetsize = j[3] - 0xC00
        tfile = os.path.join(cachefolder, "files.csv")
        i = 0
        while True:
            with open(tfile, 'w') as csvfile:
                if i == 0:
                    csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                        "step", "filepath", "size", "targetsize", "off1",
                        "off2"))
                    i += 1
                if i == 1:
                    csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                        0, outfile, os.path.getsize(outfile),
                        os.path.getsize(outfile), 0, os.path.getsize(outfile)))
                    i += 1
                if i == 2:
                    csvfile.write("{}|{}|{}|{}|{}|{}".format(
                        1, filepath, (os.path.getsize(filepath)), targetsize,
                        off1, off2))
                    i += 1
                    break
    nspname = "test.nsp"
    try:
        g = os.path.basename(filepath)
        g0 = [pos for pos, char in enumerate(g) if char == '[']
        g0 = (g[0:g0[0]]).strip()
        nspname = f"{g0} [{titleid}] [v{titleversion}] [{ctype}].nsp"
    except:
        pass
    return nspname
Example #8
0
def gen_xci_parts_spec0(filepath,target_cnmt=None,cachefolder=None,keypatch=False,export_type='csv'):
	if cachefolder==None:
		cachefolder=os.path.join(ztools_dir, '_mtp_cache_')	
	if not os.path.exists(cachefolder):
		os.makedirs(cachefolder)
	else:
		for f in os.listdir(cachefolder):
			fp = os.path.join(cachefolder, f)
			try:
				shutil.rmtree(fp)
			except OSError:
				os.remove(fp)
	program_name=None			
	files_list=sq_tools.ret_xci_offsets(filepath)
	files=list();filesizes=list()
	fplist=list()
	for k in range(len(files_list)):
		entry=files_list[k]
		fplist.append(entry[0])
	if target_cnmt==None:	
		for i in range(len(files_list)):			
			entry=files_list[i]
			cnmtfile=entry[0]	
			if cnmtfile.endswith('.cnmt.nca'):
				target_cnmt=cnmtfile
				break
	for i in range(len(files_list)):
		entry=files_list[i]
		cnmtfile=entry[0]
		if cnmtfile.endswith('.cnmt.nca') and target_cnmt==cnmtfile:
			f=squirrelXCI(filepath)
			titleid,titleversion,base_ID,keygeneration,rightsId,RSV,RGV,ctype,metasdkversion,exesdkversion,hasHtmlManual,Installedsize,DeltaSize,ncadata=f.get_data_from_cnmt(cnmtfile)
			f.flush()
			f.close()
			for j in range(len(ncadata)):
				row=ncadata[j]
				# print(row)
				if row['NCAtype']!='Meta' and row['NCAtype']!='Program':
					test1=str(row['NcaId'])+'.nca';test2=str(row['NcaId'])+'.ncz'
					if test1 in fplist or test2 in fplist:
						# print(str(row['NcaId'])+'.nca')
						if test1 in fplist:
							files.append(str(row['NcaId'])+'.nca')
							filesizes.append(int(row['Size']))
						elif test2 in fplist:	
							files.append(str(row['NcaId'])+'.ncz')
							for k in range(len(files_list)):
								entry=files_list[k]
								if entry[0]==test2:				
									filesizes.append(int(entry[3]))	
									break
			for j in range(len(ncadata)):
				row=ncadata[j]						
				if row['NCAtype']=='Meta':
					# print(str(row['NcaId'])+'.cnmt.nca')
					files.append(str(row['NcaId'])+'.cnmt.nca')
					filesizes.append(int(row['Size']))	
			for j in range(len(ncadata)):
				row=ncadata[j]
				# print(row)
				if row['NCAtype']=='Program':
					test1=str(row['NcaId'])+'.nca';test2=str(row['NcaId'])+'.ncz'
					if test1 in fplist or test2 in fplist:
						# print(str(row['NcaId'])+'.nca')
						if test1 in fplist:
							files.append(str(row['NcaId'])+'.nca')
							filesizes.append(int(row['Size']))
						elif test2 in fplist:	
							files.append(str(row['NcaId'])+'.ncz')
							for k in range(len(files_list)):
								entry=files_list[k]
								if entry[0]==test2:				
									filesizes.append(int(entry[3]))	
									break
			break			
	f.flush()
	f.close()						
	outheader = sq_tools.gen_nsp_header(files,filesizes)	
	properheadsize=len(outheader)
	# print(properheadsize)
	# print(bucketsize)
	i=0;sum=properheadsize;
	for file in files:
		# print(file)
		# print(filesizes[i])
		if i<(len(files)-1):
			sum+=filesizes[i]
		i+=1
	# print(sum)
	# print(sum/bucketsize)
	multiplier=math.ceil(sum/bucketsize)
	# print(multiplier)
	remainder = bucketsize*multiplier - sum
	# print(bucketsize*multiplier)
	xci=squirrelXCI(filepath)
	outfile=os.path.join(cachefolder, "0")
	written=0;
	outf = open(outfile, 'w+b')		
	outf.write(outheader)	
	written+=len(outheader)
	movoffset=0
	for fi in files:
		for nspF in xci.hfs0:
			if str(nspF._path)=="secure":
				for nca in nspF:	
					if nca._path==fi:
						nca=Nca(nca)
						crypto1=nca.header.getCryptoType()
						crypto2=nca.header.getCryptoType2()	
						if crypto2>crypto1:
							masterKeyRev=crypto2
						if crypto2<=crypto1:	
							masterKeyRev=crypto1						
						crypto = aes128.AESECB(Keys.keyAreaKey(Keys.getMasterKeyIndex(masterKeyRev), nca.header.keyIndex))
						hcrypto = aes128.AESXTS(uhx(Keys.get('header_key')))	
						gc_flag='00'*0x01					
						crypto1=nca.header.getCryptoType()
						crypto2=nca.header.getCryptoType2()					
						if nca.header.getRightsId() != 0:				
							nca.rewind()	
							if crypto2>crypto1:
								masterKeyRev=crypto2
							if crypto2<=crypto1:	
								masterKeyRev=crypto1	
							from mtp_tools import get_nca_ticket
								check,titleKey=get_nca_ticket(filepath,fi)
								if check==False:
									sys.exit("Can't verify titleckey")						
							titleKeyDec = Keys.decryptTitleKey(titleKey, Keys.getMasterKeyIndex(int(masterKeyRev)))							
							encKeyBlock = crypto.encrypt(titleKeyDec * 4)
							if str(keypatch) != "False":
								t = tqdm(total=False, unit='B', unit_scale=False, leave=False)								
								if keypatch < nca.header.getCryptoType2():
									encKeyBlock,crypto1,crypto2=squirrelXCI.get_new_cryptoblock(squirrelXCI,nca, keypatch,encKeyBlock,t)	
								t.close()
						if nca.header.getRightsId() == 0:
							nca.rewind()				
							encKeyBlock = nca.header.getKeyBlock()	
							if str(keypatch) != "False":
								t = tqdm(total=False, unit='B', unit_scale=False, leave=False)									
								if keypatch < nca.header.getCryptoType2():
									encKeyBlock,crypto1,crypto2=squirrelXCI.get_new_cryptoblock(squirrelXCI,nca,keypatch,encKeyBlock,t)					
								t.close()									
						nca.rewind()					
						i=0				
						newheader=xci.get_newheader(nca,encKeyBlock,crypto1,crypto2,hcrypto,gc_flag)		
						outf.write(newheader)
						written+=len(newheader)
						nca.seek(0xC00)	
						movoffset+=0xC00
						if (str(nca.header.contentType) != 'Content.PROGRAM'):
							data=nca.read()	
							nca.close()
							outf.write(data)
							written+=len(data)
						break					
					else:pass
Example #9
0
def gen_mxci_parts(input_files, cachefolder=None, keypatch=False):
    from listmanager import calculate_name
    if keypatch != False:
        try:
            keypatch = int(keypatch)
        except:
            keypatch = False
    if cachefolder == None:
        cachefolder = os.path.join(ztools_dir, '_mtp_cache_')
    if not os.path.exists(cachefolder):
        os.makedirs(cachefolder)
    else:
        for f in os.listdir(cachefolder):
            fp = os.path.join(cachefolder, f)
            try:
                shutil.rmtree(fp)
            except OSError:
                os.remove(fp)
    end_name, prlist = calculate_name(input_files, romanize=True, ext='.xci')
    print(f"Calculated name {end_name}")
    outheader, properheadsize, sz, files = gen_multi_file_header(
        prlist, input_files)
    properheadsize = len(outheader)
    outfile = os.path.join(cachefolder, "0")
    outf = open(outfile, 'w+b')
    outf.write(outheader)
    # print(properheadsize)
    # print(bucketsize)
    i = 0
    sum = properheadsize
    for fi in files:
        for filepath in input_files:
            if filepath.endswith('xci'):
                xci = squirrelXCI(filepath)
                written = 0
                for nspF in xci.hfs0:
                    if str(nspF._path) == "secure":
                        for nca in nspF:
                            if nca._path == fi:
                                nca = Nca(nca)
                                crypto1 = nca.header.getCryptoType()
                                crypto2 = nca.header.getCryptoType2()
                                if crypto2 > crypto1:
                                    masterKeyRev = crypto2
                                if crypto2 <= crypto1:
                                    masterKeyRev = crypto1
                                crypto = aes128.AESECB(
                                    Keys.keyAreaKey(
                                        Keys.getMasterKeyIndex(masterKeyRev),
                                        nca.header.keyIndex))
                                hcrypto = aes128.AESXTS(
                                    uhx(Keys.get('header_key')))
                                gc_flag = '00' * 0x01
                                crypto1 = nca.header.getCryptoType()
                                crypto2 = nca.header.getCryptoType2()
                                if nca.header.getRightsId() != 0:
                                    nca.rewind()
                                    if crypto2 > crypto1:
                                        masterKeyRev = crypto2
                                    if crypto2 <= crypto1:
                                        masterKeyRev = crypto1
                                    from mtp_tools import get_nca_ticket
                                    check, titleKey = get_nca_ticket(
                                        filepath, fi)
                                    if check == False:
                                        sys.exit("Can't verify titleckey")
                                    titleKeyDec = Keys.decryptTitleKey(
                                        titleKey,
                                        Keys.getMasterKeyIndex(
                                            int(masterKeyRev)))
                                    encKeyBlock = crypto.encrypt(titleKeyDec *
                                                                 4)
                                    if str(keypatch) != "False":
                                        t = tqdm(total=False,
                                                 unit='B',
                                                 unit_scale=False,
                                                 leave=False)
                                        if keypatch < nca.header.getCryptoType2(
                                        ):
                                            encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                                squirrelXCI, nca, keypatch,
                                                encKeyBlock, t)
                                        t.close()
                                if nca.header.getRightsId() == 0:
                                    nca.rewind()
                                    encKeyBlock = nca.header.getKeyBlock()
                                    if str(keypatch) != "False":
                                        t = tqdm(total=False,
                                                 unit='B',
                                                 unit_scale=False,
                                                 leave=False)
                                        if keypatch < nca.header.getCryptoType2(
                                        ):
                                            encKeyBlock, crypto1, crypto2 = squirrelXCI.get_new_cryptoblock(
                                                squirrelXCI, nca, keypatch,
                                                encKeyBlock, t)
                                        t.close()
                                nca.rewind()
                                i = 0
                                newheader = xci.get_newheader(
                                    nca, encKeyBlock, crypto1, crypto2,
                                    hcrypto, gc_flag)
                                outf.write(newheader)
                                written += len(newheader)
                                nca.seek(0xC00)
                                break
                            else:
                                pass
                xci.flush()
                xci.close()
            elif filepath.endswith('nsp'):
                nsp = squirrelNSP(filepath)
                written = 0
                for nca in nsp:
                    if nca._path == fi:
                        nca = Nca(nca)
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if crypto2 > crypto1:
                            masterKeyRev = crypto2
                        if crypto2 <= crypto1:
                            masterKeyRev = crypto1
                        crypto = aes128.AESECB(
                            Keys.keyAreaKey(
                                Keys.getMasterKeyIndex(masterKeyRev),
                                nca.header.keyIndex))
                        hcrypto = aes128.AESXTS(uhx(Keys.get('header_key')))
                        gc_flag = '00' * 0x01
                        crypto1 = nca.header.getCryptoType()
                        crypto2 = nca.header.getCryptoType2()
                        if nca.header.getRightsId() != 0:
                            nca.rewind()
                            if crypto2 > crypto1:
                                masterKeyRev = crypto2
                            if crypto2 <= crypto1:
                                masterKeyRev = crypto1
                            from mtp_tools import get_nca_ticket
                            check, titleKey = get_nca_ticket(filepath, fi)
                            if check == False:
                                sys.exit("Can't verify titleckey")
                            titleKeyDec = Keys.decryptTitleKey(
                                titleKey,
                                Keys.getMasterKeyIndex(int(masterKeyRev)))
                            encKeyBlock = crypto.encrypt(titleKeyDec * 4)
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelNSP.get_new_cryptoblock(
                                        squirrelNSP, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        if nca.header.getRightsId() == 0:
                            nca.rewind()
                            encKeyBlock = nca.header.getKeyBlock()
                            if str(keypatch) != "False":
                                t = tqdm(total=False,
                                         unit='B',
                                         unit_scale=False,
                                         leave=False)
                                if keypatch < nca.header.getCryptoType2():
                                    encKeyBlock, crypto1, crypto2 = squirrelNSP.get_new_cryptoblock(
                                        squirrelNSP, nca, keypatch,
                                        encKeyBlock, t)
                                t.close()
                        nca.rewind()
                        i = 0
                        newheader = nsp.get_newheader(nca, encKeyBlock,
                                                      crypto1, crypto2,
                                                      hcrypto, gc_flag)
                        outf.write(newheader)
                        written += len(newheader)
                        nca.seek(0xC00)
                        break
                    else:
                        pass
                nsp.flush()
                nsp.close()
    outf.flush()
    outf.close()
    tfile = os.path.join(cachefolder, "files.csv")
    with open(tfile, 'w') as csvfile:
        csvfile.write("{}|{}|{}|{}|{}|{}\n".format("step", "filepath", "size",
                                                   "targetsize", "off1",
                                                   "off2"))
        csvfile.write("{}|{}|{}|{}|{}|{}\n".format(0, outfile,
                                                   properheadsize + written,
                                                   properheadsize, 0,
                                                   properheadsize))
        k = 0
        l = 0
        for fi in files:
            for filepath in input_files:
                if filepath.endswith('xci'):
                    files_list = sq_tools.ret_xci_offsets(filepath)
                elif filepath.endswith('nsp'):
                    files_list = sq_tools.ret_nsp_offsets(filepath)
                for j in files_list:
                    if j[0] == fi:
                        csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                            k + 1, outfile, properheadsize + written, 0xC00,
                            (properheadsize + l * 0xC00),
                            (properheadsize + (l * 0xC00) + 0xC00)))
                        off1 = j[1] + 0xC00
                        off2 = j[2]
                        targetsize = j[3] - 0xC00
                        csvfile.write("{}|{}|{}|{}|{}|{}\n".format(
                            k + 2, filepath, (os.path.getsize(filepath)),
                            targetsize, off1, off2))
                        break
            k += 2
            l += 1
    return end_name