- fix challenge exchange and tickets
 - full encrypted convo to splash
 - proper encryption sessions to maintain working RC4 stream
 - proper nodejs versioning, encryption working
 - minor changes, included mini tutorial, version inc
 - fix file loading issues
This commit is contained in:
zefie
2021-07-11 18:28:53 -04:00
parent 5662357981
commit 6300348e2e
44 changed files with 1879 additions and 422 deletions

3
.gitignore vendored
View File

@@ -360,4 +360,5 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
FodyWeavers.xsd
/hacktv_updsrv/ServiceLogPost/1626307222_warning_812bf30600b002bb

33
README.md Normal file
View File

@@ -0,0 +1,33 @@
# wtv minisrv node.js
The ***wtv minisrv***, or "***hacktv_updsrv***" project is a node.js project that provides a mini WebTV Server, with wtv-encryption support for advanced level box access.
This open source server is in alpha status. Use at your own risk.
### Current status:
- Can encrypt and decrypt SECURE ON and arbitrary encrypted data
- Can handle psuedo encryption (box sends SECURE ON but does not encrypt)
- Can handle client "relogin" and "reconnect" events
### Current issues:
- Probably can't handle more than one box at a time
- Power cycling box and re-connecting via ConnectSetup may invalidate encryption until server is restarted
- wtv-update:/update does not yet function as intended
### Feature Todo:
- Test and enable flashrom flashing functionality (at least for LC2 and higher)
- (maybe) Proper wtv-star (generic service outage page) support (maybe useful for allowing a unit to multiple sub-minisrvs).
- (maybe) implement HTTP proxy (needs to be able to defluff most of the web, think retro WAP converter)
- (maybe) enable "internet mode" (let user outside of minisrv)
- (maybe) wtvchat stuff
- (probably not) url tokenizer
### How To Use:
- Install [node.js](https://nodejs.org/en/download/)
- Download a snapshot (either of master, or of any commit/branch/relase/tag etc)
- Extract zip somewhere and enter that directory with a command prompt
- Run `npm install`
- Check any configuration (services.json)
- Run `node app.js`
- Test with a WebTV Viewer or connect with a real box
- To connect with a real box, you will need to open ports in your firewall and have a way to connect your WebTV (and preferably reroute 10.0.0.1 to the server)

370
hacktv_updsrv/.gitignore vendored Normal file
View File

@@ -0,0 +1,370 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# ServiceLogPost Posted Logs
ServiceLogPost/*_*
# Large files not pertaining to the service code
ServiceVault/wtv-flashrom/content/*
ServiceVault/wtv-music/content/*
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
/hacktv_updsrv/ServiceLogPost/1626307222_warning_812bf30600b002bb

View File

@@ -1,3 +0,0 @@
# hacktv_updsrv

Binary file not shown.

View File

@@ -1,7 +0,0 @@
GROUP name=hacktv version=!VERS! root=file://Disk/Browser/ service-owned
display Updating HackTV Files...
sync Games/Games.html Games.html
sync Games/cSetup.html cSetup.html
sync Games/updater.html updater.html
sync MattMan/Tricks/tricks.html tricks.html
END-GROUP

View File

@@ -1,48 +0,0 @@
<html>
<head>
<meta
http-equiv=refresh
content="0;url=client:Fetch?source=http://wtv.zefie.com/hacktv/?diskmap=update&root=file://Disk/Browser&group=hacktv"
>
<display downloadsuccess="client:ShowAlert?message=HackTV%20Update%20was%20successful%21&buttonlabel2=Go%20to%20HackTV&action2=file%3A%2F%2FDisk%2FBrowser%2FGames%2FGames.html&buttonlabel1=Okay&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true" downloadfail="client:ShowAlert?message=HackTV%20Update%20failed...&buttonlabel1=Okay...&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true">
<title>Retrieving Files</title>
</head>
<body bgcolor=#0 text=#42CC55 fontsize=large hspace=0 vspace=0>
<table cellspacing=0 cellpadding=0>
<tr>
<td width=104 height=74 valign=middle align=center bgcolor=3B3A4D>
<img src="file://disk/browser/Games/hacktv4.gif" width=86 height=64>
<td width=20 valign=top align=left bgcolor=3B3A4D>
<spacer>
<td colspan=2 width=436 valign=middle align=left bgcolor=3B3A4D>
<font color=D6DFD0 size=+2><blackface><shadow>
<spacer type=block width=1 height=4>
<br>
Retrieving Files
</shadow>
</blackface>
</font>
<tr>
<td width=104 height=20>
<td width=20>
<td width=416>
<td width=20>
<tr>
<td colspan=2>
<td>
<font size=+1>
Your HackTV Box is downloading updates from zefie's server.
<p>This may take a while.
</font>
<tr>
<td colspan=2>
<td>
<br><br>
<font color=white>
<progressindicator name="downloadprogress"
message="Checking for updates..."
height=40 width=250>
</font>
</table>
</body>
</html>

View File

@@ -1,32 +0,0 @@
ANDY........z.
.`.6[......8(&.S.....}...lIa.;...b..c..d....e...f..g%.c*I.h..i!...j).k.B.lH.m.=C5*@.n
.1].oQ.t..Ip.().{..Isetdtr..(C.);.Idoelay..1>..z..1....rC...}M.q.(..r..R.lIs|...w(...P)e..P;..r..0.t0.u.,~..v.,lIw;..1.v.){.i(.!..D).b;..'.P='.D.o.i(.-.>....j....IUx..y[.za.A..N8.B.=..C.C
.UzN.D..A..y~..:...NC2<..y3.N....}.a....e{2.g.$.
...=.v.[.A{.D..d
(."M.A(.....r..a....f.u...ep.G...PQ...R.."E..F|.UG..H..F..F.....F.E%.r0.-.&.+ F..r-U.I.I.(lIJ..K.......j J|.J.w/C2
.K.D..R,.%..H#LH"M.!.NM".!progr?esstex7 ....$..percen.tage..6...dGirt.".!')O...*IP.$Q.1*I.R..S
.TF0;?.0..<..U.04..#.."version>P0GC9.|.0. .#....!g..hon}es0tings..|@1n!T.EC8i.r.!...y.1?<..
.0U..2..v1..3.)1..4.34.44..0.printf.(.STS: cou.ldn't .. .size of CROa..5....+i.z.3(
.9.)<
.R.!R .>@S).4.A.C1S..464?4W>45W5R..6=..F..A."..:f0^.8.. 15..w.9..8.I.;I.x...FON.E@%x, le?n=%d, ....+.,t.+w.,.!.... /Q.AP. ...@.....a.rF..Q>.Z!..
P.-G.%+..$..e..2'.SV."W@P*I.X..Y... Z..a.a.CIba.[C.40.].aIfl.ush..send.s.QSATI3
|.R!*SENT ....b..linf1Q.,WC3?..1.Q;.R.....8@.b}+fw .query go.t '%s'.,...i }efirmw.areb6. ..15..]mb..vb.`..c.m.`M.,SV1..001_WEBT.V-K56_DLB.0EDc8.!q..YE....;E.;.....b.?.....U S:.:..:i.sRockwel.l."..."..\....p|....+MR=0............CX. t.est retu.rned......O..`m....e...#S2.20.../..........._ x....+k1....0&.X#..s3&P..t6............Xt.....
Z....&.;2
.c%a..d....e.C.......g. .O.A....2.p@....Ii...A;61.AcIj...0.#.k#.7#.l5.8.5.mv.^.G.9G.*.InQ0S1.aT.oZ..pb.Iq..r ..s..t..u..=.e.nablemod.em..tflow.controlN../S].baud^.>..pOeIv ...D2GV1E.0.3..3..T...P@..@..@..
@...@.........d.[[ound v..@ .@jP, di9s..x. 56..]....p.....`.4....F..|!X....!a...+.+MS=11,.....[...,.,SS.51=3*.....R...@ss@.38=0S.30=180S9.5=36;.L3&.Q5&K.c. u ..qVP.5.I &(I...nec..with.videoa..)QN... B.M..e...... 5.S6=101X.r:...4XNr....0GC7o.. x.. ......#1.!....2"..6. .p1.8?.I..d.I.9}.....K.|....,.(./4.cw-.hack@...F.C.., .. S10=S%sS...,.A,.1.,.1,~1e.:.9....+....0$..0=S3...#...2.."./.1.....m......a.."A ...b..,.s.n..Z ......@..m9..1=@..P.'...(.(.1...(
. (.Q.6P...'. P.. .P.C..|..}5.&P.C..-.h.-.b..3..9.2.4.Cetw.indow....;0.~j.Iw.cx,pl.Iy~o~o~o~e..v..@Jc6dA.....bB..g2.cC.g3ndD.I..b8<....V.M..L.H..Y....-J...R.O...&!..g-Us..QLD pref.ix.+W.....S,..%..........5.5..KG9.9.9...!q..r.A.E..F......P.<=.....<...wa.itfo..H..p...),C7;.6....p.fig ....L.b..?: TIMEO.UT f.\qj. OWK (V.=..)=..I...x..G....C..... from .l.,..Y.d..S...T7.B.G..H..I
....statu..C.6F.J..C.B.....:...8.p..._.,S.lp*.*.%.orce.hook.....rt....K>.lIL.5.M|.N...R..=I.|._parser/esul_p@4.0.r5.b....@Ic9..e>.C..#T.NC4?255464...].V. -- %d /%s (..c...p...k....,..j#b{.&x.<C38l.,.A..C>..r..Up...oa
.....%`..: ...7.$..q%..q&.N.O CARRIE.R-.<-...- DI.ALTONE\.5x\.....BUSY...7..{@. ANSW.......G......L.C....C..ed!...e..*.&.*..-.C.p.b....E.E.~..0..2?..3G.b2..9.pm.2>.2.....34<.:<.<...)4...pd..4.......5.55.4....1c...|...i
>.p;#>.N..79>....?'..4s...83. .*5.M.....58....C.&.96.%:.........8.B. .A.jP.1R..9unknown..3..9|.<.<..?.>..6..O..PJ.J.J."J.QJ..@..R..J.uS..:..lIT..qU..0.<.*IV...W..X..\.h.....?,SISP-.R...1.+..,..C1?.u0...b .....e.*......ork..nu.mbeyq......=.IYKaA.....=I9E....,C2#......G....3..a..=.....+0C....>..d.!.&G.&...t....|b.....Z..s....P|...........A.TDP...
9...= v.R.......,:"....x.....Pb....k@P..D.....&.!<4.!b@...B r.c .W. r.r..., .ti.r...x..9B.,>.I.a.ler..SErr...!.: Your. recei.. .can.... to. WebTV. .Please{.t.a..Custom.0.Care at. 1-800-4.69-3288..J.. 3.i(e"...p.......6........ ........&.}.$g..c..#E. .3=..#;....%3L....0]...f.ancy....l..6.:.....S;G...6..Id
.A.O.IIir.G1.CuHlIew....Iw....... z..y......46.MC
...%w.0eL.N.<..D..w..lin...B.A&.@06..H.b.1...E.....U.. @.W...P....`..1eh.8kd...=..Iatoi..Dr...(.B.~)3A...i.@R..Bdela..PC;.S,Pf.12@..n..r.2c...g]0.odd...S..{.\.QNmU....<z.>....Q..r.q......T.....E.IgoA=.5S.h
...s.dter{at.q, dc...prot..com.p.p.!..h!.......g/'.d.i.@!.l.j.8...9..r,l*I.kb.r..=X.V.T...Q!.P.....XQ.p,.X......al. g.../%sa.x.v...v....7dx..26...@.i.aP.failur.e,.$2...;.....| .s.....,`.....O.....l:.m,.nt....u7.nam.1.....pass#.d@vP*.........o.a.5.2.2..rtpp.4.T.u..Ap.P..)...=.AP/CHA?P auth..0..:0.0.PP ne.?0ia.AI.e_"r.C;0.........O..s.c..)<.....F.WARNING.@{S &. low.3..q6..R5q....rT"..Ys.#t.#u.#.c..[C3y.....0.`)U..8.Iii.>..NT%...,S.#..'....).08..I.1u.tefc.1^..v...V...k.:"p..M...sUs@1.. wi..".A/.D..l$r.". ..cv.dlIJ..J...system_>.`boxfe. ...la..
.J..55G464b..2..IU.AJ..-a..-a..w........b...n."D.s.uppor.%.6.....u.h.......R..Ag........k.x..RlPyA.sPz..A
.uB..C.SlIDf.cEbUS#...tiyA.C76:7f1#.#....yea..gA:....dl`/.local...I.g.nCk.NC7.;2(.{.<b...e.L....av.Pt./.a...,M...%..........(b......,.x....A...yofwee.[AN...hr...U....min{0'.`...l..
.i.*...F*.*I.G..H..hrJ..K.........#.].....?rycoun.Qy.8"..tM.=Iq..n..
.nex..seq.Len.....T.qC.==.f(..=..;R..<....Pu.....=IL...u,..[z..]Z.K.,@....s..c..rMG.-....y.|..E..-7.r.%.]..qe$...W.mQ00.E.:.%.as..J..I........!r.r.r..r.r.r .1....ma.i..?.?.*..=@rA.4.DL.[C5.T.T...lINp.ti.ck~.le#
.!.7. g..v.O*..Q......+<C9..PU...qc..A...rog3..s.iJ.fullp.op....S.......r..E....,C2.....o.Q.+L...s.:'.&!z...?.....R.)..~...+.su{cc.., in.@.]0A..(..-..)./C3<..:. ..?...:.. #..d.;.@i.i........1Y..X. u...i(Z.[PP.]&.8V...2..0...3..)|~././. >./.z./._ 7_..../.. 6..c./.. 5 ..........Z.. ..7.........lIS:..L^.Premp<..to 6pl.......a$cVO.}.,=.c...[C8n...SD...%s .@........f.bf.f.f.f.A/.Nj.j...c.......WebTV...8....0.Wai.A...+.1...a.IS..n.swee.].=.\....-...M.....V
O.(..(...yI. ....v..4.4....*....rn...k@..L(..T..U...IV..r..Sw.tv_6......S.....base.ts.f .. 77 (.ANI=(E.et;))^Eani.X..0.P.E..ldIl.....k..W....5...'......O...#.*.vi.c..9=39==s33.`
.<32...n..Io.di.=SS ....[.`]...>a[.0...@j...)..6..8,.4G.66.V.o@J 7Y.../P,..Y.5w.......
....4..g.....:.*.V.P*...G...5.qh .J..h..4....=..d....;..$.69;....;.>J...Y...J. 1a.v.:A....._...q:.Q.6;..o.5.Y.Q...h.......?.a...<......Z.." h. "+..U..{.....l..,s?..r;..1C.47..7.... .\.. .zb~!..P.8.i..P.X)....Y......,*IZ@.*Ia9c. ..lIy.q...(.=S18006.13819..6.=;Sa .mis..6..@...:.:.:.H.8.w..BUGd.....a1.....`.....i.........,..B...c.\.b...c..d..$.fcJ..g0.h..=.@,.U@-.@..@/.@0...BW.A.*C64..+P.I1..`...o.U....u.... for~..%d:%02...........l..p..r.;.S.S1. |.D.@S.D...e...e.\.\.\..\.L.A.......>.".^...S-a*.-...,..(...\.....;.<c=X.....

View File

@@ -0,0 +1,46 @@
if (socket_session_data[socket.id].ssid != null && !sec_session[socket_session_data[socket.id].ssid]) {
sec_session[socket_session_data[socket.id].ssid] = new WTVSec();
sec_session[socket_session_data[socket.id].ssid].IssueChallenge();
sec_session[socket_session_data[socket.id].ssid].set_incarnation(request_headers['wtv-incarnation']);
}
var contype = "text/tellyscript";
var skip_tellyscript = false;
// if relogin, skip tellyscript
if (query['relogin']) {
contype = "text/html"; // skip tellyscript
sec_session[socket_session_data[socket.id].ssid].ticket_b64 = null; // clear old ticket
}
headers = `200 OK
Connection: Keep-Alive
wtv-initial-key: ` + issueWTVInitialKey(socket) + `
Content-Type: `+ contype + `
wtv-service: reset
` + getServiceString('wtv-1800') + `
` + getServiceString('wtv-star') + `
` + getServiceString('wtv-head-waiter') + `
` + getServiceString('wtv-flashrom') + `
wtv-boot-url: wtv-1800:/preregister?relogin=true
wtv-visit: wtv-head-waiter:/login?
wtv-client-time-zone: GMT -0000
wtv-client-time-dst-rule: GMT
wtv-client-date: `+strftime("%a, %d %b %Y %H:%M:%S", new Date(new Date().toUTCString()))+` GMT`;
// if relogin, skip tellyscript
var romtype = null;
if (!query['relogin'] && skip_tellyscript == false) {
var romtype = getSessionData(socket_session_data[socket.id].ssid, 'wtv-client-rom-type');
}
switch (romtype) {
case "US-LC2-disk-0MB-8MB":
data = getFile("LC2/LC2_OISP_5555732_56k.tok", true);
break;
default:
data = '';
break;
}

View File

@@ -1,33 +0,0 @@
var ssid = initial_headers['wtv-client-serial-number'] || null;
if (ssid != null && !sec_session[ssid]) {
sec_session[ssid] = new WTVNetworkSecurity();
sec_session[ssid].IssueChallenge();
}
headers = `200 OK
Connection: Keep-Alive
Content-Type: text/tellyscript
wtv-initial-key: ` + sec_session[ssid].challenge_key.toString(CryptoJS.enc.Base64) + `
wtv-service: reset
wtv-service: name=wtv-1800 host=` + pubip + ` port=1615 connections=1
wtv-service: name=wtv-head-waiter host=` + pubip + ` port=1615 flags=0x04 flags=0x00000001 connections=1
wtv-service: name=htv-update host=` + pubip + ` port=1615 flags=0x04
wtv-client-time-zone: GMT -0000
wtv-client-date: `+strftime("%a, %d %b %Y %H:%M:%S", new Date(new Date().toUTCString()))+` GMT
wtv-boot-url: wtv-head-waiter:/login?
Location: wtv-head-waiter:/login?
wtv-visit: wtv-head-waiter:/login?`;
var romtype = getWTVROMType(initial_headers);
switch (romtype) {
case "US-LC2-disk-0MB-8MB":
data = fs.readFileSync(__dirname + "/ServiceVault/wtv-1800/LC2/artemis_18006138199.tok");
break;
default:
data = '';
break;
}

View File

@@ -1,4 +1,14 @@
var gourl = "wtv-1800:/finish-prereg?";
if (query['relogin']) gourl += "relogin=true";
if (request_headers['wtv-ticket']) {
gourl = "wtv-head-waiter:/login-stage-two?";
}
headers = `200 OK
Connection: Keep-Alive
wtv-expire-all: wtv-
wtv-open-isp-disabled: false
wtv-visit: wtv-1800:/offer-open-isp-suggest?`;
wtv-visit: `+ gourl + `
Content-type: text/html`;

View File

@@ -0,0 +1,98 @@
headers = `200 OK
Content-type: text/html`
data = `<html>
<head>
<title>
Updating
</title>
<display switchtowebmode transition=none nostatus nooptions skipback clearback>
</head>
<body noscroll bgcolor="#191919" text="#42CC55" link="36d5ff"
hspace=0 vspace=0 fontsize="large">
<table cellspacing=0 cellpadding=0>
<tr>
<td width=104 height=74 valign=middle align=center bgcolor="3B3A4D">
<td width=20 valign=top align=left bgcolor="3B3A4D">
<td colspan=10 width=436 valign=middle align=left bgcolor="3B3A4D">
<font color="D6DFD0" size="+2">
<blackface>
<shadow>
<br>
Updating now...
</shadow>
</blackface>
</font>
<tr>
<td colspan=12 width=560 height=10 valign=top align=left>
<tr>
<td width=104 height=10 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=68 valign=top align=left>
<td width=20 valign=top align=left>
<form action="client:poweroff">
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 width=100 height=258 valign=top align=left>
<font size=+1>
Your Internet Receiver is being<br>updated automagically.
<p> <font size=+1>
This will take forever, and then<br> your WebTV will reboot.<br><br>
</font>
</table>
<table width="100%">
<tr>
<td align="left"><font size="-1" color="#D6DFD0"><small>&nbsp; &nbsp; Receiving part `+flashrom_part+` of `+totalprts+`</small></font></td>
<td align="right"><font size="-1" color="#D6DFD0"><small>v`+flashrom_version+` (`+flashrom_type+`) &nbsp; &nbsp;</small></font></td>
</tr>
</table>
<center>
<upgradeblock width=520 height=15
`+nextrompath+`
errorurl="wtv-flashrom:/lc2-download-failed"
blockurl="wtv-flashrom:/`+rompath+`"
lastblock=`+lastpart+`
curblock="`+flashrom_part+`"
totalblocks="`+totalprts+`"></center>
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=10 height=2 valign=middle align=center bgcolor="#191919">
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 height=1 valign=top align=left>
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=10 height=2 valign=top align=left bgcolor="#191919">
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 height=4 valign=top align=left>
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 width=416 valign=top align=left>
<table cellspacing=0 cellpadding=0>
<tr>
<td width=306 valign=top align=left>
<font size="-1"><i>
</i></font><td width=112 valign=top align=right>
<font size="-1" color="#191919">
</font>
</form>
</table>
<td width=20 valign=middle align=center>
</table>
</body>
</html>`

View File

@@ -0,0 +1,50 @@
<html>
<head>
<title>
Updating failed
</title>
<display switchtowebmode transition=none nostatus nooptions skipback clearback>
</head>
<body noscroll bgcolor="#191919" text="#42CC55" link="36d5ff"
hspace=0 vspace=0 fontsize="large">
<table cellspacing=0 cellpadding=0>
<tr>
<td width=104 height=74 valign=middle align=center bgcolor="3B3A4D">
<img src="wtv-flashrom:/ROMCache/MSNLogo.gif" width=87 height=67>
<td width=20 valign=top align=left bgcolor="3B3A4D">
<img src="wtv-flashrom:/ROMCache/Spacer.gif" width=1 height=1>
<td colspan=10 width=436 valign=middle align=left bgcolor="3B3A4D">
<font color="D6DFD0" size="+2">
<blackface>
<shadow>
<img src="wtv-flashrom:/ROMCache/Spacer.gif" width=1 height=4>
<br>
Updated failed
</shadow>
</blackface>
</font>
<tr>
<td colspan=12 width=560 height=10 valign=top align=left>
<img src="wtv-flashrom:/ROMCache/S40H1.gif" width=560 height=6>
<tr>
<td width=104 height=10 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=68 valign=top align=left>
<td width=20 valign=top align=left>
<form action="client:poweroff">
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 width=100 height=258 valign=top align=left>
<font size=+1>
Update failed, gomennasai.
</body>
</html>

View File

@@ -0,0 +1,53 @@
headers = `200 OK
Content-type: text/html`
data =`<html>
<head>
<title>
Updating failed
</title>
<display switchtowebmode transition=none nostatus nooptions skipback clearback>
</head>
<body noscroll bgcolor="#191919" text="#42CC55" link="36d5ff"
hspace=0 vspace=0 fontsize="large">
<table cellspacing=0 cellpadding=0>
<tr>
<td width=104 height=74 valign=middle align=center bgcolor="3B3A4D">
<img src="wtv-flashrom:/ROMCache/MSNLogo.gif" width=87 height=67>
<td width=20 valign=top align=left bgcolor="3B3A4D">
<img src="wtv-flashrom:/ROMCache/Spacer.gif" width=1 height=1>
<td colspan=10 width=436 valign=middle align=left bgcolor="3B3A4D">
<font color="D6DFD0" size="+2">
<blackface>
<shadow>
<img src="wtv-flashrom:/ROMCache/Spacer.gif" width=1 height=4>
<br>
Updated failed
</shadow>
</blackface>
</font>
<tr>
<td colspan=12 width=560 height=10 valign=top align=left>
<img src="wtv-flashrom:/ROMCache/S40H1.gif" width=560 height=6>
<tr>
<td width=104 height=10 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=67 valign=top align=left>
<td width=20 valign=top align=left>
<td width=68 valign=top align=left>
<td width=20 valign=top align=left>
<form action="client:poweroff">
<tr>
<td width=104 valign=middle align=center>
<td width=20 valign=middle align=center>
<td colspan=9 width=100 height=258 valign=top align=left>
<font size=+1>
Update failed, gomennasai.
</body>
</html>`

View File

@@ -0,0 +1,20 @@
// willie is just a graphical frontend to a list of ROMs
// the rest of the scripts should work if you manually link to a ROM, and actually have it.
const options = new URL('http://wtv.zefie.com/willie.php?flash='+getSessionData(socket_session_data[socket.id].ssid, 'wtv-client-rom-type'))
var data_ready = false;
data = '';
const req = http.request(options, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
data += d;
})
res.on('end', function () {
data_ready = true;
});
});
headers = "200 OK\nContent-type: text/html";

View File

@@ -0,0 +1,24 @@
var challenge_response, challenge_header = '';
var gourl;
if (socket_session_data[socket.id].ssid !== null) {
if (request_headers['wtv-ticket']) {
if (request_headers['wtv-ticket'].length > 8) {
DecodeTicket(request_headers['wtv-ticket']);
sec_session[socket_session_data[socket.id].ssid].ticket_b64 = request_headers['wtv-ticket'];
//socket_session_data[socket.id].secure == true;
}
} else if (sec_session[socket_session_data[socket.id].ssid].ticket_b64 == null) {
// TODO: client should have a ticket and send it back by now, if not we should handle this correctly
}
}
headers = `200 OK
Connection: Keep-Alive
wtv-encrypted: true
wtv-ticket: `+sec_session[socket_session_data[socket.id].ssid].ticket_b64+`
wtv-expire-all: htv-
wtv-home-url: wtv-home:/home?
wtv-visit: wtv-home:/splash?
Content-Type: text/html
`;

View File

@@ -1,17 +1,95 @@
var ssid = initial_headers['wtv-client-serial-number'] || null;
var initialChallenge, challenge_response, challenge_header = '';
var challenge_response, challenge_header = '';
var gourl;
if (ssid !== null) {
if (sec_session[ssid].ticket) {
challenge_header = "wtv-ticket: "+sec_session[ssid].ticket;
if (socket_session_data[socket.id].ssid !== null) {
if (sec_session[socket_session_data[socket.id].ssid].ticket_b64 == null) {
if (request_headers['wtv-ticket']) {
if (request_headers['wtv-ticket'].length > 8) {
sec_session[socket_session_data[socket.id].ssid].DecodeTicket(request_headers['wtv-ticket']);
sec_session[socket_session_data[socket.id].ssid].ticket_b64 = request_headers['wtv-ticket'];
//socket_session_data[socket.id].secure = true;
}
} else {
challenge_response = sec_session[socket_session_data[socket.id].ssid].challenge_response;
var client_challenge_response = request_headers['wtv-challenge-response'] || null;
if (challenge_response && client_challenge_response) {
//if (challenge_response.toString(CryptoJS.enc.Base64).substring(0,85) == client_challenge_response.substring(0,85)) {
if (challenge_response.toString(CryptoJS.enc.Base64) == client_challenge_response) {
console.log(" * wtv-challenge-response success for "+socket_session_data[socket.id].ssid);
sec_session[socket_session_data[socket.id].ssid].PrepareTicket();
//socket_session_data[socket.id].secure = true;
} else {
console.log(" * wtv-challenge-response FAILED for " + socket_session_data[socket.id].ssid);
if (zdebug) console.log("Response Expected:", challenge_response.toString(CryptoJS.enc.Base64));
if (zdebug) console.log("Response Received:", client_challenge_response)
gourl = "wtv-head-waiter:/login?reissue_challenge=true";
}
} else {
gourl = "wtv-head-waiter:/login?no_response=true";
}
}
}
}
if (gourl) {
headers = `200 OK
Connection: Keep-Alive
wtv-open-isp-disabled: false
wtv-visit: `+ gourl + `
Content-type: text/html`;
data = '';
}
else {
var namerand = Math.floor(Math.random() * 100000);
var nickname = 'HackTVUsr_' + namerand;
var userid = '1'+ Math.floor(Math.random() * 1000000000000000000);
var offline_user_list = CryptoJS.enc.Latin1.parse("<user-list>\n\t<user userid=\"" + userid + " user-name=\"" + nickname + "\" first-name=\"HackTV\" last-name=\"User \"" + namerand + "\" password=\"\" mail-enabled=\"true\" />\n</user-list>").toString(CryptoJS.enc.Base64);
headers = `200 OK
wtv-ticket: `+sec_session[ssid].ticket+`
headers = `200 OK
Connection: Keep-Alive
wtv-encrypted: true
wtv-client-time-zone: GMT -0000
wtv-client-date: `+ strftime("%a, %d %b %Y %H:%M:%S", new Date(new Date().toUTCString())) + ` GMT
wtv-country: US
wtv-language-header: en-US,en
wtv-visit: client:closeallpanels
wtv-expire-all: client:closeallpanels
wtv-offline-user-list: `+offline_user_list+`
wtv-bypass-proxy: true
wtv-ticket: `+ sec_session[socket_session_data[socket.id].ssid].ticket_b64 + `
wtv-messagewatch-checktimeoffset: off
wtv-input-timeout: 14400
wtv-connection-timeout: 90
wtv-fader-timeout: 900
wtv-ssl-log-url: wtv-log:/log
wtv-smartcard-inserted-message: Contacting service
user-id: `+userid+`
wtv-transition-override: off
wtv-allow-dsc: true
wtv-messenger-enable: 0
wtv-noback-all: wtv-
wtv-service: reset
`+ getServiceString('all') + `
wtv-boot-url: wtv-1800:/preregister?relogin=true
wtv-user-name: `+ nickname + `
wtv-human-name: `+ nickname + `
wtv-irc-nick: `+ nickname + `
wtv-home-url: wtv-home:/home?
wtv-domain: wtv.zefie.com
wtv-inactive-timeout: 0
wtv-connection-timeout: 90
wtv-show-time-enabled: true
wtv-fader-timeout: 900
wtv-tourist-enabled: true
wtv-connection-timeout: 180
wtv-ssl-timeout: 240
wtv-login-timeout: 7200
wtv-open-isp-disabled: false
wtv-log-url: wtv-log:/log
wtv-demo-mode: 0
wtv-wink-deferrer-retries: 3
wtv-offline-mail-enable: false
wtv-name-server: 8.8.8.8
wtv-visit: wtv-home:/splash?
Content-Type: text/html`;
data = sec_session[ssid].EncryptKey1('hehe! stage two! and its encrypted!');
}

View File

@@ -1,57 +1,56 @@
var ssid = initial_headers['wtv-client-serial-number'] || null;
var initialChallenge, challenge_response, challenge_header = '';
var gourl = "wtv-head-waiter:/login?reissue_challenge=true";
var challenge_response, challenge_header = '';
if (query['reissue_challenge']) {
gourl = "client:activ";
}
if (ssid !== null) {
if (sec_session[ssid].ticket_b64 == null) {
if (initial_headers['wtv-ticket']) {
DecodeTicket(initial_headers['wtv-ticket']);
sec_session[ssid].ticket_b64 = initial_headers['wtv-ticket'];
challenge_header = "wtv-ticket: "+initial_headers['wtv-ticket'];
} else {
challenge_response = sec_session[ssid].challenge_response;
var client_challenge_response = initial_headers['wtv-challenge-response'] || null;
if (challenge_response && client_challenge_response) {
if (challenge_response.toString(CryptoJS.enc.Base64).substring(0,85) == client_challenge_response.substring(0,85)) {
console.log(" * wtv-challenge-response success for "+ssid);
sec_session[ssid].PrepareTicket();
challenge_header = "wtv-ticket: "+sec_session[ssid].ticket_b64;
var gourl = "wtv-head-waiter:/login-stage-two?";
} else {
challenge_header = "wtv-whatever: meh";
gourl = "wtv-1800:/preregister?";
}
} else {
if (sec_session[ssid].challenge_b64 == null) {
challenge_header = "wtv-whatever: meh";
gourl = "wtv-1800:/preregister?";
} else {
challenge_header = "wtv-challenge: "+sec_session[ssid].challenge_b64;
}
if (socket_session_data[socket.id].ssid !== null) {
if (request_headers['wtv-ticket']) {
if (sec_session[socket_session_data[socket.id].ssid].ticket_b64 == null) {
if (request_headers['wtv-ticket'].length > 8) {
sec_session[socket_session_data[socket.id].ssid].DecodeTicket(request_headers['wtv-ticket']);
sec_session[socket_session_data[socket.id].ssid].ticket_b64 = request_headers['wtv-ticket'];
}
}
} else {
challenge_header = "wtv-ticket: "+sec_session[ssid].ticket_b64;
challenge_response = sec_session[socket_session_data[socket.id].ssid].challenge_response;
var client_challenge_response = request_headers['wtv-challenge-response'] || null;
if (challenge_response && client_challenge_response) {
if (challenge_response.toString(CryptoJS.enc.Base64).substring(0,85) == client_challenge_response.substring(0,85)) {
console.log(" * wtv-challenge-response success for "+socket_session_data[socket.id].ssid);
sec_session[socket_session_data[socket.id].ssid].PrepareTicket();
} else {
challenge_header = "wtv-challenge: "+issueWTVChallenge(socket);
}
} else {
challenge_header = "wtv-challenge: "+issueWTVChallenge(socket);
}
}
}
/*
if (request_headers) {
var cookiedata = {};
Object.keys(request_headers).forEach(function (k) {
switch (k) {
case "wtv-capability-flags":
case "wtv-system-version":
case "wtv-client-rom-type":
case "wtv-client-bootrom-version":
case "wtv-system-chipversion":
case "wtv-system-sysconfig":
case "wtv-system-cpuspeed":
cookiedata[k] = request_headers[k];
break;
}
});
}
*/
headers = `200 OK
Connection: Keep-Alive
Expires: Wed, 09 Oct 1991 22:00:00 GMT
wtv-expire-all: wtv-head-waiter:
wtv-service: name=wtv-log host=` + pubip + ` port=1615 connections=1
`+getServiceString('wtv-log')+`
wtv-log-url: wtv-log:/log
`+challenge_header+`
wtv-relogin-url: wtv-1800:/preregister?relogin=true
wtv-reconnect-url: wtv-1800:/preregister?reconnect=true
wtv-visit: `+gourl+`
Content-length: 0
wtv-visit: wtv-head-waiter:/login-stage-two?
Content-type: text/html`;
data = '';

View File

@@ -1,2 +0,0 @@
var wtvtest = new WTVNetworkSecurity();
wtvtest.Test();

View File

@@ -0,0 +1,46 @@
headers =`200 OK
Connection: Keep-Alive
wtv-expire-all: wtv-home:/splash
Content-type: text/html`
if (getSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption')) {
var cryptstatus = "<a href='client:showalert?message=Your%20WebTV%20Unit%20sent%20us%20a%20request%20for%20SECURE%20ON%2C%20but%20did%20not%20encrypt%20any%20data%2C%20nor%20will%20accept%20it.%20However%2C%20we%20send%20the%20wtv-encryption%20flag%20to%20roll%20with%20it%2C%20enabling%20%27psuedo-encryption%27.%20Nothing%20is%20encrypted%2C%20but%20the%20box%20trusts%20us.%20This%20will%20probably%20go%20away%20if%20you%20reload%20or%20change%20pages.&buttonaction1=client:donothing&buttonlabel1=Oh%2C%20okay...'>Psuedo-encrypted</a>";
} else {
var cryptstatus = ((socket_session_data[socket.id].secure === true) ? "Encrypted" : "Not Encrypted")
}
data =`<html>
<head>
<title>Home for minsrv</title>
<DISPLAY showwhencomplete options showoptions noscroll>
</head>
<body bgcolor="black" link="gold" vlink="gold" alink="gold" text="gold">
<script>
function ax(a) {
document.open("text/url");
document.write(a);
document.close();
}
</script>
<h1>Welcome to `+ z_title + `</h1>
<h3>Encryption Status: `+cryptstatus+`</h3>`
if (socket_session_data[socket.id].secure) {
data += '<span size="-1">Encryption Key (Server): ' + sec_session[socket.id].session_key2.toString(CryptoJS.enc.Hex)+'<br>';
data += 'Encryption Key (Client): ' + sec_session[socket.id].session_key1.toString(CryptoJS.enc.Hex)+'</span><br><br>';
}
data += `<h4>Working stuff</h4>
<a href="client:relog">client:relog (direct)</a><br>
<a href="wtv-tricks:/blastcache?">Clear Cache</a><br>
<h4>zefie's server only</h4>
<a href="wtv-music:/content/index.html">Music Collection</a><br>
<h4>Test Stuff (probably broken)</h4>
<a href="wtv-update:/update?" selected>HackTV Updater Test</a><br>
<a href="wtv-flashrom:/willie">Ultra Willies</a><br>
<a href="client:showalert?message=If%20you%20choose%20to%20disconnect%20and%20return%20to%20HackTV%20home%2C%20you%20may%20not%20be%20able%20to%20reconnect%20to%20the%20update%20server%20until%20you%20power%20cycle%20your%20box.%3Cbr%3E%3Cbr%3EAre%20you%20sure%20you%20would%20like%20to%20go%20offline%3F&buttonlabel1=No&buttonaction1=client:donothing&buttonlabel2=Yes&buttonaction2=wtv-tricks%3A%2Fgo-offline%3Ftitle%3DHackTV%2520Home">Disconnect and go to HackTV Home</a><br>
<!-- <a href="buttonaction2=wtv-home:/unlock">Unlock Full Client (Options, Goto, etc)</a><br> -->
</body>
</html>`

View File

@@ -0,0 +1,25 @@
200 OK
Connection: Keep-Alive
wtv-expire-all: htv-
Content-type: text/html
<html>
<title>Engaging zefie...</title>
<head>
<display nooptions showwhencomplete nostatus skipback clearback fontsize=medium>
<meta
http-equiv=refresh
content="5; url=wtv-home:/home?"
>
</head>
<body bgcolor="#000000" text="#449944">
<bgsound src="file://ROM/Sounds/Splash.mid">
<center>
<img src="wtv-star:/images/HackTVLogo.gif">
<br>
<spacer type=block height=98 width=21>
<br>
</center>
</body>
</html>

View File

@@ -1,10 +1,17 @@
console.log(initial_headers);
// write posted log data to disk. should be decrypted by this point (if it was encrypted) if the crypto stream didn't break
if (request_headers['post_data']) {
var fullpath = __dirname + "/ServiceLogPost/" + Math.floor(new Date().getTime() / 1000) + "_" + query['type'];
if (socket_session_data[socket.id].ssid) fullpath += "_" + socket_session_data[socket.id].ssid;
fullpath = fullpath.replace(/\\/g, "/");
fs.writeFileSync(fullpath, request_headers['post_data'].toString(CryptoJS.enc.Hex), "Hex");
console.log("Wrote POST log data from", socket_session_data[socket.id].ssid, "to", fullpath, "on", socket.id);
}
headers = `200 OK
Connection: Keep-Alive
Expires: `+strftime("%a, %d %b %Y %H:%M:%S", new Date((new Date().toUTCString()) + 10))+` GMT
Content-length: 0
Content-type: text/html`;
Content-length: 0`;
data = '';

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -0,0 +1,17 @@
200 OK
wtv-noback-all: wtv-
wtv-expire-all: wtv-
Content-type: text/html
<html>
<head>
<meta
http-equiv=refresh
content="1; url=wtv-home:/home?"
>
<body bgcolor="black" text="gold" link="gold" vlink="gold" alink="gold">
Successfully expired service URL cache<br>
Any previously cached pages should be reloaded from the network.<br><br>
<a href="wtv-home:/home">Go Home</a>
</body>
</html>

View File

@@ -0,0 +1,42 @@
headers = `200 OK
wtv-noback-all: wtv-
wtv-expire-all: wtv-
Content-type: text/html
wtv-service: reset
`+getServiceString('wtv-1800');
// HackTV Homepage is default
var url="file://Disk/Browser/Games/Games.html";
if (query['url']) {
url = query['url'];
}
data = `<html>
<head>
<title>Going offline...</title>
<DISPLAY notvaudio allowoffline hideoptions switchtowebmode>
<body bgcolor="black" text="gold" onload="onLoad">
<script type="text/javascript">
function disconnect() {
location.href = "client:HangUpPhone?allow-reconnect=no";
}
function go(url) {
location.href = url;
}
if (window.location) {
setTimeout('disconnect()',100);
setTimeout('go("`+url+`")',200);
}
</script>
<br><br>
`
if (query['title']) {
data += "Going offline and loading "+decodeURI(query['title'])+", please wait!";
} else {
data += "Please wait a moment.";
}
data += "</body>\n</html>";

View File

@@ -0,0 +1,10 @@
GROUP name=Browser version=!VERS! root=file://Disk/Browser/Games/
display Updating HackTV Files...
sync Games.html content/htvupdate/Games/Games.html
sync cSetup.html content/htvupdate/Games/cSetup.html
END-GROUP
GROUP name=Browser version=!VERS! root=file://Disk/Browser/MattMan/
display Updating HackTV Files...
sync Tricks/tricks.html content/htvupdate/MattMan/Tricks/tricks.html
END-GROUP

View File

@@ -81,7 +81,7 @@ if (document.images) {
<li><a href="file://disk/Browser/MattMan/html/index.html" onmouseover="document.r1.src=pic9.src;">HTML Viewer</a>
<li><a href="file://disk/Browser/MattMan/Tricks/tricks.html" onmouseover="document.r1.src=pic6.src;">HackTV Tricks</a>
<li><a href="file://disk/Browser/Games/cSetup.html" onmouseover="document.r1.src=pic10.src;">Connect Setup</a>
<li><a href="client:ConfirmConnectSetup?ServiceType=bypass&bootURL=http://wtv.zefie.com/hacktv/index.php&homeURL=http://wtv.zefie.com/hacktv/update/updater.html&nameServer=208.67.222.222&useEncryption=false&Connect=Connect">Test</a>
<li><font size="-1"><sup>NEW!</sup</font><a href="client:ConfirmConnectSetup?machine=192.168.11.8&port=1615&ServiceType=custom&useEncryption=true&useDirectConnection=true&Connect=Connect"> Check for Updates</a>
<!--li>Boot <a href="client:boota?NA" onmouseover="document.r1.src=pic11.src;">2.9</a> - <a href="client:boota?NA" onmouseover="document.r1.src=pic12.src;" onmouseout="document.r1.src=pic13.src;">2.1</a-->
</td></tr>
</table>

View File

@@ -0,0 +1,39 @@
var content_dir = service_dir + '/content/';
var diskmap_dir = content_dir + '/diskmaps/';
if (initial_headers['post_data']) {
console.log(initial_headers['post_data'].toString('CryptoJS.enc.Latin1'))
}
if (query['diskmap']) {
if (fs.lstatSync(diskmap_dir + query['diskmap'] + ".txt")) {
var diskmap_data = fs.readFileSync(diskmap_dir + query['diskmap'] + ".txt").toString();
// try to parse diskmap and get an accurate timestamp for webtv versioning
// check all files in the diskmap and return the timestamp of the most recently modified
data = '';
var latest_file_ts = 0;
diskmap_data.split("\n").forEach(function (v) {
if (v.indexOf(" sync ") != -1) {
v = v.trim();
var vcon = v.substring(v.indexOf("content/"));
vcon = vcon.replace("content/", content_dir)
var vconstat = Math.floor(fs.lstatSync(vcon).mtimeMs / 1000);
if (vconstat > latest_file_ts) {
latest_file_ts = vconstat
}
// todo read client post and only give whats needed
// instead of all that is available
// vconstat has the mtime of each file, we need to parse the post_data
data += v + "\n";
} else {
data += v + "\n";
}
});
//data = diskmap_data.replace("!VERS!", latest_file_ts);
}
}
headers = `200 OK
Content-type: text/download-list`

View File

@@ -2,10 +2,10 @@
<head>
<meta
http-equiv=refresh
content="0;url=client:Fetch?source=htv-update:/upd?diskmap=update&root=file://Disk/Browser&group=hacktv"
content="0;url=client:Fetch?group=Browser&source=wtv-update:/sync%3Fdiskmap%3Dhtvupdate&message=Downloading%20updates..."
>
<display downloadsuccess="client:ShowAlert?message=HackTV%20Update%20was%20successful%21&buttonlabel2=Go%20to%20HackTV&action2=file%3A%2F%2FDisk%2FBrowser%2FGames%2FGames.html&buttonlabel1=Okay&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true" downloadfail="client:ShowAlert?message=HackTV%20Update%20failed...&buttonlabel1=Okay...&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true">
<title>Retrieving Files</title>
<display downloadsuccess="client:ShowAlert?message=HackTV%20Update%20was%20successful%21&buttonlabel2=Go%20to%20HackTV&action2=wtv-tricks:/go-offline%3Ftitle%3DHackTV%20Home&buttonlabel1=Okay&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true" downloadfail="client:ShowAlert?message=HackTV%20Update%20failed...&buttonlabel1=Okay...&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true">
<title>HackTV Updater</title>
</head>
<body bgcolor=#0 text=#42CC55 fontsize=large hspace=0 vspace=0>
<table cellspacing=0 cellpadding=0>
@@ -18,7 +18,7 @@
<font color=D6DFD0 size=+2><blackface><shadow>
<spacer type=block width=1 height=4>
<br>
Retrieving Files
Download HackTV Updates
</shadow>
</blackface>
</font>
@@ -31,7 +31,7 @@
<td colspan=2>
<td>
<font size=+1>
Your HackTV Box is downloading updates from zefie's server.
Your HackTV Unit is downloading updates.
<p>This may take a while.
</font>
<tr>
@@ -40,7 +40,7 @@
<br><br>
<font color=white>
<progressindicator name="downloadprogress"
message="Checking for updates..."
message="Preparing..."
height=40 width=250>
</font>
</table>

View File

@@ -1,3 +1,4 @@
200 OK
Content-Type: text/url
client:ShowAlert?message=HackTV%20Update%20was%20successful%21&buttonlabel2=Go%20to%20HackTV&action2=file%3A%2F%2FDisk%2FBrowser%2FGames%2FGames.html&buttonlabel1=Okay&buttonaction1=client:goback&image=file://disk/browser/Games/hacktv2.gif&noback=true

View File

@@ -7,76 +7,105 @@ const strftime = require('strftime');
const net = require('net');
const CryptoJS = require('crypto-js');
const mime = require('mime-types');
var WTVNetworkSecurity = require('./wtvsec.js');
const crc16 = require('node-crc16');
var WTVSec = require('./wtvsec.js');
var zdebug = true;
var pubip = "192.168.11.8";
var port = 1615;
var ports = [];
var service_vault_dir = __dirname + "/ServiceVault";
function getServiceString(service) {
if (service === "all") {
var out = "";
Object.keys(services_configured.services).forEach(function (k) {
out += services_configured.services[k].toString() + "\n";
});
return out;
} else {
if (!services_configured.services[service]) {
throw ("SERVICE ERROR: Attempted to provision unconfigured service: " + service)
} else {
return services_configured.services[service].toString();
}
}
}
var ssid_data = new Array();
var sec_session = new Array();
var socket_buffer = new Array();
var socket_session_data = new Array();
function getWTVIncarnation(headers, ssid = null) {
var incarnation = null;
headers.some(function (v) {
if (v.substring(0, 15) === "wtv-incarnation") {
incarnation = v.split(': ')[1].replace("\r", "");
return incarnation != null;
}
});
if (ssid != null && incarnation != null) {
if (sec_session[ssid] != null) {
sec_session[ssid].set_incarnation(incarnation);
if (zdebug) console.log(" * Updated wtv-incarnation for " + ssid + " to " + incarnation + " ...");
}
}
return incarnation;
var script_processing_timeout = 10; // seconds
var overrides = new Array();
//overrides['initial_key'] = "CC5rWmRUE0o=";
//overrides['challenge'] = "0kjyqIYAu0ziFBbSERN6DGaZ6S0fT+DBUCtpHCJ4lpuM7CbXdAm+x83BIDoJYztd1Z+5KFZ7ghmb3LJCT/6mhWUYkqqKOyfPRW8ZIdbICK/CV+Kxm8EUjRXZSk/97tsmFpH3hcCJ7C2TBw+TX38uQQ==";
function getSessionData(ssid, key = null) {
if (typeof (ssid_data[ssid]) === 'undefined') return null;
if (key == null) return ssid_data[ssid];
else if (ssid_data[ssid][key]) return ssid_data[ssid][key];
else return null;
}
function getWTVROMType(headers, ssid = null) {
var romtype = null;
headers.some(function (v) {
if (v.substring(0, 19) === "wtv-client-rom-type") {
romtype = v.split(': ')[1].replace("\r", "");
return romtype != null;
}
});
return romtype;
function setSessionData(ssid, key, value) {
if (typeof (ssid_data[ssid]) === 'undefined') ssid_data[ssid] = new Array();
ssid_data[ssid][key] = value;
}
function getPublicIP() {
var options = {
host: 'www.planeptune.org',
path: '/ip.php'
function getFile(path, deps = false) {
var dir = null;
if (deps) dir = __dirname + "/ServiceDeps/";
else dir = __dirname + "/ServiceVault/";
if (fs.lstatSync(dir + path).isFile()) {
return fs.readFileSync(dir + path, {
encoding: null,
flags: 'r'
});
}
return null;
}
function issueWTVInitialKey(socket) {
if (overrides['initial_key']) {
sec_session[socket_session_data[socket.id].ssid].initial_shared_key = CryptoJS.enc.Base64.parse(overrides['initial_key']);
sec_session[socket_session_data[socket.id].ssid].current_shared_key = CryptoJS.enc.Base64.parse(overrides['initial_key']);
sec_session[socket_session_data[socket.id].ssid].challenge_key = CryptoJS.enc.Base64.parse(overrides['initial_key']);
return overrides['initial_key'];
} else {
return sec_session[socket_session_data[socket.id].ssid].challenge_key.toString(CryptoJS.enc.Base64);
}
}
function issueWTVChallenge(socket) {
if (overrides['challenge']) {
sec_session[socket_session_data[socket.id].ssid].challenge_response = sec_session[socket_session_data[socket.id].ssid].ProcessChallenge(overrides['challenge']);
return overrides['challenge'];
} else {
return sec_session[socket_session_data[socket.id].ssid].IssueChallenge();
}
var request = https.get(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
return data;
});
});
}
function doErrorPage(code) {
var headers, data = null;
switch (code) {
case 404:
data = "The resource you requested could not be found.";
headers = "HTTP/1.1 404 Not Found\r\n";
data = "The service could not find the requested page.";
headers = "404 "+data+"\r\n";
headers += "Content-Type: text/html\r\n";
break;
case 500:
case 400:
data = "An internal server error has occured.";
headers = "HTTP/1.1 500 HackTV has ran into a technical problem.\r\n";
headers = "400 HackTV ran into a technical problem.\r\n";
headers += "Content-Type: text/html\r\n";
break;
default:
// what we send when we did not detect a wtv-url.
// e.g. when a pc browser connects
data = "Hello, stranger!";
headers = "HTTP/1.1 200 OK\r\n";
headers += "Content-Type: text/html\r\n";
@@ -85,9 +114,18 @@ function doErrorPage(code) {
return new Array(headers, data);
}
function processPath(path, initial_headers = new Array(), query = new Array()) {
function getConType(path) {
// custom contype for flashrom
if (path.indexOf("wtv-flashrom") && (path.substring(path.length - 4, path.length) == ".rom" || path.substring(path.length - 5, path.length) == ".brom")) {
return "binary/x-wtv-flashblock";
}
return mime.lookup(path);
}
async function processPath(socket, path, request_headers = new Array(), query = new Array(), service_name) {
var headers, data = null;
var request_is_direct_file = false;
path = path.replace(/\\/g, "/");
try {
try {
// try to see if the exact request exists
@@ -100,29 +138,42 @@ function processPath(path, initial_headers = new Array(), query = new Array()) {
if (request_is_direct_file) {
// file exists, read it and return it
console.log(" * Found " + path + " to handle request");
var contype = mime.lookup(path);
data = fs.readFileSync(path);
headers = "200 OK\r\n"
console.log(" * Found " + path + " to handle request (Direct File Mode) [Socket " + socket.id +"]");
var contype = getConType(path);
data = new Uint8Array(fs.readFileSync(path)).buffer;
headers = "200 OK\n"
headers += "Content-Type: " + contype;
} else if (fs.existsSync(path + ".txt")) {
// raw text format, entire payload expected (headers and content)
console.log(" * Found " + path + ".txt to handle request");
var fdat = fs.readFileSync(path + ".txt").toString();
headers = fdat.split("\r\n\r\n")[0];
data = fdat.split("\r\n\r\n")[1];
console.log(" * Found " + path + ".txt to handle request (Raw TXT Mode) [Socket " + socket.id +"]");
var file_raw = fs.readFileSync(path + ".txt").toString();
if (file_raw.indexOf("\n\n") > 0) {
var file_raw_split = file_raw.split("\n\n");
headers = file_raw_split[0];
file_raw_split.shift();
data = file_raw_split.join("\n");
} else if (file_raw.indexOf("\r\n\r\n") > 0) {
var file_raw_split = file_raw.split("\r\n\r\n");
headers = file_raw_split[0].replace(/\r/g, "");
file_raw_split.shift();
data = file_raw_split.join("\r\n");
} else {
headers = fdat;
}
} else if (fs.existsSync(path + ".js")) {
// js scripting, process with vars, must set 'headers' and 'data' appropriately.
// loaded script will have r/w access to any JavaScript vars this function does.
// any query args are in an array named 'query'
console.log(" * Found " + path + ".js to handle request");
var fdat = fs.readFileSync(path + ".js").toString();
eval(fdat);
console.log(" * Found " + path + ".js to handle request (JS Interpreter mode) [Socket " + socket.id + "]");
var service_dir = service_vault_dir.replace(/\\/g,"/") + "/" + service_name;
socket_session_data[socket.id].starttime = Math.floor(new Date().getTime() / 1000);
var jscript_eval = fs.readFileSync(path + ".js").toString();
eval(jscript_eval);
} else if (fs.existsSync(path + ".html")) {
// Standard HTML with no headers, WTV Style
console.log(" * Found " + path + ".html to handle request");
console.log(" * Found " + path + ".html to handle request (HTML Mode) [Socket " + socket.id +"]");
data = fs.readFileSync(path + ".html").toString();
headers = "200 OK\r\n"
headers = "200 OK\n"
headers += "Content-Type: text/html"
} else {
var errpage = doErrorPage(404);
@@ -137,128 +188,508 @@ function processPath(path, initial_headers = new Array(), query = new Array()) {
if (typeof headers !== "string") {
headers = headers.toString();
}
if (headers.indexOf("\r") === -1) {
headers = headers.replace("\n", "\r\n");
}
} else {
var errpage = doErrorPage(500);
var errpage = doErrorPage(400);
headers = errpage[0];
data = errpage[1];
console.log(" * Scripting or Data error: Headers were not defined. (headers,data) as follows:")
console.log(headers,data)
}
if (data === null) {
data = '';
}
if (typeof data !== "string") {
data = data.toString();
}
} catch (e) {
var errpage = doErrorPage(500);
var errpage = doErrorPage(400);
headers = errpage[0];
data = errpage[1] + "<br><br><pre>" + e.toString() + "</pre>";
data = errpage[1] + "<br><br>The interpreter said:<br><pre>" + e.toString() + "</pre>";
console.log(e);
}
if (headers.toLowerCase().indexOf("content-length") === -1) {
headers += "\r\nContent-Length: " + data.length;
}
return new Array(headers, data);
}
function processURL(initial_headers, socket) {
async function processURL(socket, request_headers) {
if (request_headers === null) {
return;
}
var shortURL, headers, data = "";
var query = new Array();
if (initial_headers['request_url'].indexOf('?') >= 0) {
shortURL = initial_headers['request_url'].split('?')[0];
var qraw = initial_headers['request_url'].split('?')[1];
if (qraw.length > 0) {
qraw = qraw.split("&");
for (let i = 0; i < qraw.length; i++) {
query[qraw[i].split("=")[0]] = qraw[i].split("=")[1];
}
if (zdebug) {
console.log("URL Request has query arguments:")
console.log(query);
}
}
} else {
shortURL = initial_headers['request_url'];
}
if (request_headers['request_url']) {
if (request_headers['request_url'].indexOf('?') >= 0) {
shortURL = request_headers['request_url'].split('?')[0];
var qraw = request_headers['request_url'].split('?')[1];
if (qraw.length > 0) {
qraw = qraw.split("&");
for (let i = 0; i < qraw.length; i++) {
var k = qraw[i].split("=")[0];
if (k) {
query[k] = qraw[i].split("=")[1];
}
}
if (shortURL.indexOf(':/') >= 0) {
var ssid = initial_headers['wtv-client-serial-number'];
if (ssid != null) {
console.log(" * Request for " + initial_headers['request_url'] + " from WebTV SSID " + ssid);
console.log(" * Request query:", query);
}
} else {
console.log(" * Request for " + initial_headers['request_url']);
shortURL = request_headers['request_url'];
}
// assume webtv since there is a :/ in the GET
var urlToPath = __dirname + "/ServiceVault/" + shortURL.split(':/')[0] + "/" + shortURL.split(':/')[1];
if (zdebug) console.log(initial_headers);
var result = processPath(urlToPath, initial_headers, query);
if (result[0] == null) {
var errpage = doErrorPage(404);
headers = errpage[0];
data = errpage[1];
} else {
headers = result[0];
data = result[1];
}
} else {
switch (shortURL) {
default:
var errpage = doErrorPage(200);
if (shortURL.indexOf(':/') >= 0) {
var ssid = socket_session_data[socket.id].ssid;
if (ssid == null) {
ssid = request_headers['wtv-client-serial-number'];
}
var reqverb = "Request";
if (request_headers['encrypted'] || request_headers['secure']) {
reqverb = "Encrypted " + reqverb;
}
if (request_headers['psuedo-encryption']) {
reqverb = "Psuedo-encrypted " + reqverb;
}
if (ssid != null) {
console.log(" * "+reqverb+" for " + request_headers['request_url'] + " from WebTV SSID " + ssid, 'on', socket.id);
} else {
console.log(" * "+reqverb+" for " + request_headers['request_url'], 'on', socket.id);
}
// assume webtv since there is a :/ in the GET
var service_name = shortURL.split(':/')[0];
var urlToPath = service_vault_dir.replace(/\\/g, "/") + "/" + service_name + "/" + shortURL.split(':/')[1];
console.log(request_headers);
var result = await processPath(socket, urlToPath, request_headers, query, service_name);
if (result[0] == null) {
// error processing path
var errpage = doErrorPage(404);
headers = errpage[0];
data = errpage[1];
break;
} else {
headers = result[0];
data = result[1];
}
} else {
switch (shortURL) {
default:
var errpage = doErrorPage(200);
headers = errpage[0];
data = errpage[1];
break;
}
}
} else {
// error reading headers (no request_url provided)
var errpage = doErrorPage(400);
headers = errpage[0];
data = errpage[1]
socket_session_data[socket.id].close_me = true;
}
// headers to object
if (typeof headers != 'object') {
var headers_obj = {};
var inc_headers = 1;
headers.split('\n').forEach(function (d) {
if (d.length > 0) {
if (d.indexOf(":") > 0 && !/^([0-9]{3} )/.test(d.substring(0, 4))) {
var d = d.split(':');
var header_name = d[0];
d.shift();
if (headers_obj[header_name] != null) {
header_name = header_name + "_" + inc_headers;
inc_headers++;
}
headers_obj[header_name] = d.join(':').replace("\r", "");
if (headers_obj[header_name].substring(0, 1) == " ") {
headers_obj[header_name] = headers_obj[header_name].substring(1);
}
} else if (/^([0-9]{3} )/.test(d.substring(0, 4))) {
headers_obj['http_response'] = d.replace("\r", "");
}
}
});
} else {
header_obj = headers;
}
if (!headers_obj['Connection']) {
headers_obj['Connection'] = "Keep-Alive";
headers_obj = moveObjectElement('Connection','http_response', headers_obj);
}
if (request_headers['psuedo-encryption'] || getSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption')) {
request_headers['psuedo-encryption'] = true;
headers_obj['wtv-encrypted'] = true;
headers_obj = moveObjectElement('wtv-encrypted', 'Connection', headers_obj);
}
// set wtv-encrypted and put it near the top of the headers (unknown if needed)
if (socket_session_data[socket.id].secure == true) {
var clen = null;
if (typeof data.length !== 'undefined') {
clen = data.length;
} else if (typeof data.byteLength !== 'undefined') {
clen = data.byteLength;
}
headers_obj['wtv-encrypted'] = true;
headers_obj = moveObjectElement('wtv-encrypted', 'Connection', headers_obj);
if (clen > 0) {
console.log(" * Encrypting response to client ...")
var data_type = typeof (data);
if (typeof (data) === 'string') {
data = CryptoJS.enc.Utf8.parse(data);
}
if (data.constructor === ArrayBuffer) {
data = CryptoJS.lib.WordArray.create(data);
}
var enc_data = sec_session[socket.id].Encrypt(1,data);
data = enc_data;
}
}
if (!headers_obj["Content-length"] && !headers_obj["Content-length"]) {
if (typeof data.length !== 'undefined') {
headers_obj['Content-Length'] = data.length;
} else if (typeof data.byteLength !== 'undefined') {
headers_obj['Content-Length'] = data.byteLength;
}
}
var toClient = headers + "\r\n\r\n" + data;
console.log(headers);
socket.write(toClient);
socket.destroy();
headers = "";
console.log(headers_obj);
Object.keys(headers_obj).forEach(function (k) {
if (k == "http_response") {
headers += headers_obj[k] + "\r\n";
} else {
if (k.indexOf('_') >= 0) {
var j = k.split('_')[0];
headers += j + ": " + headers_obj[k] + "\n";
} else {
headers += k + ": " + headers_obj[k] + "\n";
}
}
});
var toClient = null;
if (typeof data == 'string') {
toClient = headers + "\n" + data;
socket.write(toClient);
} else if (typeof data == 'object') {
if (socket_session_data[socket.id].secure_headers == true) {
var enc_headers = sec_session[socket.id].Encrypt(1,headers+"\n");
socket.write(new Uint8Array(concatArrayBuffer(enc_headers, data)));
} else {
socket.write(new Uint8Array(concatArrayBuffer(Buffer.from(headers + "\n"), data)));
}
}
if (headers_obj['Connection']) {
if (headers_obj['Connection'].toLowerCase() == "close") {
socket.destroy();
}
}
}
function concatArrayBuffer(buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
}
var server = net.createServer(function (socket) {
socket.setEncoding("utf8"); //set data encoding (either 'ascii', 'utf8', or 'base64')
function moveObjectElement(currentKey, afterKey, obj) {
var result = {};
var val = obj[currentKey];
delete obj[currentKey];
var next = -1;
var i = 0;
if (typeof afterKey == 'undefined' || afterKey == null) afterKey = '';
Object.keys(obj).forEach(function (k) {
var v = obj[k];
if ((afterKey == '' && i == 0) || next == 1) {
result[currentKey] = val;
next = 0;
}
if (k == afterKey) { next = 1; }
result[k] = v;
++i;
});
if (next == 1) {
result[currentKey] = val;
}
if (next !== -1) return result; else return obj;
}
socket.on('data', function (data) {
var url = "";
var headers = new Array();
if (typeof data === "string") {
data.split('\n').forEach(function (d) {
if (d != "") {
if (d == "SECURE ON") {
headers['secure'] = true;
function headersAreStandard(string, verbose) {
// the test will see the binary compressed/enrypted data as ASCII, so a generic "isAscii"
// is not suffuicent. This checks for characters expected in unecrypted headers, and returns
// true only if every character in the string matches the regex. Once we know the string is binary
// we can better process it with the raw base64 data in processHeaders() below.
var test = /^([A-Za-z0-9\+\/\=\-\.\,\ \;\:\?\&\r\n\(\)\%\<\>\_]{8,})$/.test(string);
if (verbose) {
if (zdebug) console.log(" # Request is ascii: " + test);
if (zdebug) console.log(" # Request is SECURE ON: " + /^SECURE ON/.test(string));
}
return test;
}
async function processHeaders(socket, data_hex, returnHeadersBeforeSecure = false, encryptedRequest = false) {
var url = "";
var data = CryptoJS.enc.Latin1.stringify(CryptoJS.enc.Hex.parse(data_hex));
var headers = new Array();
if (typeof data === "string") {
if (data.length > 1) {
if (data.indexOf("\r\n\r\n") != -1) {
data = data.split("\r\n\r\n")[0];
} else {
data = data.split("\n\n")[0];
}
if (headersAreStandard(data, (!returnHeadersBeforeSecure && !encryptedRequest))) {
data.split('\n').forEach(function (d) {
if (d.length > 0) {
if (/^SECURE ON/.test(d)) {
headers['secure'] = true;
//socket_session_data[socket.id].secure_headers = true;
}
if (d.indexOf(":") > 0 && d.indexOf(":/") == -1) {
headers[d.split(':')[0]] = (d.split(':')[1]).replace("\r", "");
if (headers[d.split(':')[0]].substring(0, 1) == " ") {
headers[d.split(':')[0]] = headers[d.split(':')[0]].substring(1);
}
} else if (/^(GET |PUT |POST)$/.test(d.substring(0, 4))) {
headers['request'] = d.replace("\r", "");
headers['request_url'] = (d.split(' ')[1]).replace("\r", "");
}
}
if (d.indexOf(": ") > 0) {
headers[d.split(': ')[0]] = (d.split(': ')[1]).replace("\r","");
} else if (/^(GET |PUT |POST)$/.test(d.substring(0, 4))) {
headers['request'] = d.replace("\r", "");
headers['request_url'] = (d.split(' ')[1]).replace("\r", "");
});
} else if (!returnHeadersBeforeSecure) {
// if its a POST request, assume its a binary blob and not encrypted (dangerous)
if (!encryptedRequest) {
// its not a POST and it 1failed the headersAreStandard test, so we think this is an encrypted blob
if (socket_session_data[socket.id].secure != true) {
// first time so reroll sessions
sec_session[socket.id] = new WTVSec();
sec_session[socket.id].IssueChallenge();
if (zdebug) console.log(" # [ UNEXPECTED BINARY BLOCK ] First sign of encryption, re-creating RC4 sessions for socket id",socket.id);
sec_session[socket.id].SecureOn();
socket_session_data[socket.id].secure = true;
}
var enc_data = CryptoJS.enc.Hex.parse(data_hex.substring(header_length * 2));
if (enc_data.sigBytes > 0) {
var dec_data = CryptoJS.lib.WordArray.create(sec_session[socket.id].Decrypt(0,enc_data));
var secure_headers = await processHeaders(socket, dec_data.toString(CryptoJS.enc.Hex), true, true);
headers['encrypted'] = true;
Object.keys(secure_headers).forEach(function (k, v) {
headers[k] = secure_headers[k];
});
}
}
});
console.log(headers);
if (headers['secure'] === true) {
// assume we have an ssid if we are this far
sec_session[headers['wtv-client-serial-number']].SecureOn();
if (!headers['request_url']) {
headers['request_url'] = "wtv-head-waiter:/login-stage-two?";
}
}
processURL(headers,this);
if (headers['wtv-client-serial-number'] != null) {
socket_session_data[socket.id].ssid = headers['wtv-client-serial-number'];
}
if (headers['wtv-client-rom-type'] != null) {
if (socket_session_data[socket.id].ssid) {
setSessionData(socket_session_data[socket.id].ssid, 'wtv-client-rom-type', headers['wtv-client-rom-type']);
}
}
if (headers['wtv-incarnation'] != null) {
if (sec_session[socket.id]) {
sec_session[socket.id].set_incarnation(headers['wtv-incarnation']);
} else {
setSessionData(socket_session_data[socket.id].ssid, 'incarnation', headers['wtv-incarnation'])
}
}
if (returnHeadersBeforeSecure) {
headers = await checkForPostData(socket, headers, data, data_hex, returnHeadersBeforeSecure);
return headers;
}
if (headers['secure'] === true) {
if (!sec_session[socket.id]) {
console.log(" * Starting new WTVSec instance on socket", socket.id);
sec_session[socket.id] = new WTVSec();
sec_session[socket.id].DecodeTicket(headers['wtv-ticket']);
sec_session[socket.id].ticket_b64 = headers['wtv-ticket'];
if (getSessionData(socket_session_data[socket.id].ssid, 'incarnation')) {
sec_session[socket.id].incarnation = getSessionData(socket_session_data[socket.id].ssid, 'incarnation');
}
sec_session[socket.id].SecureOn();
}
if (socket_session_data[socket.id].secure != true) {
// first time so reroll sessions
if (zdebug) console.log(" # [ SECURE ON BLOCK ("+socket.id+")]");
socket_session_data[socket.id].secure = true;
}
if (!headers['request_url']) {
if (data_hex.indexOf("0d0a0d0a")) {
// \r\n\r\n
var header_length = data.length + 4;
} else if (data_hex.indexOf("0a0a")) {
// \n\n
var header_length = data.length + 2;
}
var enc_data = CryptoJS.enc.Hex.parse(data_hex.substring(header_length * 2));
if (enc_data.sigBytes > 0) {
if (headersAreStandard(enc_data.toString(CryptoJS.enc.Latin1), (!returnHeadersBeforeSecure && !encryptedRequest))) {
// some builds (like our targeted 3833), send SECURE ON but then unencrypted headers
if (zdebug) console.log(" # Psuedo-encrypted Request (SECURE ON)", "on", socket.id);
// don't actually encrypt output
headers['psuedo-encryption'] = true;
setSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption', true);
socket_session_data[socket.id].secure = false;
var secure_headers = await processHeaders(socket, enc_data.toString(CryptoJS.enc.Hex), true);
} else {
// SECURE ON and detected encrypted data
setSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption', false);
var dec_data = CryptoJS.lib.WordArray.create(sec_session[socket.id].Decrypt(0, enc_data))
var secure_headers = await processHeaders(socket, dec_data.toString(CryptoJS.enc.Hex), true);
if (zdebug) console.log(" # Encrypted Request (SECURE ON)", "on", socket.id);
}
// Merge new headers into existing headers object
Object.keys(secure_headers).forEach(function (k, v) {
headers[k] = secure_headers[k];
});
}
}
}
headers = await checkForPostData(socket, headers, data, data_hex);
return headers;
} else {
// socket error, terminate it.
socket.destroy();
}
}
return null;
}
async function checkForPostData(socket, headers, data, data_hex) {
if (headers['request']) {
if (headers['request'].substring(0, 4) == "POST") {
if (data_hex.indexOf("0d0a0d0a") != -1) {
// \r\n\r\n
var header_length = data.length + 4;
} else if (data_hex.indexOf("0a0a") != -1) {
// \n\n
var header_length = data.length + 2;
}
if (socket_session_data[socket.id].secure == true) {
var enc_data = CryptoJS.enc.Hex.parse(data_hex.substring(header_length * 2));
if (enc_data.sigBytes > 0) {
if (headersAreStandard(enc_data.toString(CryptoJS.enc.Latin1))) {
// some builds (like our targeted 3833), send SECURE ON but then unencrypted headers
if (zdebug) console.log(" # Psuedo-encrypted POST Content (SECURE ON)", "on", socket.id);
// don't actually encrypt output
headers['psuedo-encryption'] = true;
setSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption', true);
socket_session_data[socket.id].secure = false;
headers['post_data'] = await processHeaders(socket, enc_data.toString(CryptoJS.enc.Hex), true);
} else {
// SECURE ON and detected encrypted data
setSessionData(socket_session_data[socket.id].ssid, 'box-does-psuedo-encryption', false);
headers['post_data'] = CryptoJS.lib.WordArray.create(sec_session[socket.id].Decrypt(0, enc_data))
if (zdebug) console.log(" # Encrypted POST Content (SECURE ON)", "on", socket.id);
}
}
} else {
if (zdebug) console.log(" # Unencrypted POST Content", "on", socket.id);
headers['post_data'] = CryptoJS.enc.Hex.parse(data_hex.substring(header_length * 2));
}
}
}
return headers;
}
async function cleanupSocket(socket) {
try {
console.log(" * Destroying old WTVSec instance on disconnected socket", socket.id);
delete socket_buffer[socket.id];
delete socket_session_data[socket.id];
delete sec_session[socket.id];
socket.end();
} catch (e) {
console.log(" # Could not clean up socket data for socket ID", socket.id, e);
}
};
async function handleSocket(socket) {
// create unique socket id with client address and port
socket.id = parseInt(crc16.checkSum(Buffer.from(String(socket.remoteAddress) + String(socket.remotePort), "utf8")).toString("hex"),16);
socket_session_data[socket.id] = [];
socket.setEncoding('hex'); //set data encoding (either 'ascii', 'utf8', or 'base64')
socket.on('data', function (data_hex) {
socket.setTimeout(300);
if (socket_buffer[socket.id]) {
socket_buffer[socket.id].concat(CryptoJS.enc.Hex.parse(data_hex));
} else {
socket_buffer[socket.id] = CryptoJS.enc.Hex.parse(data_hex);
}
});
socket.on('timeout', async function () {
socket.setTimeout(0);
var phead = await processHeaders(this, socket_buffer[socket.id].toString(CryptoJS.enc.Hex));
processURL(this, phead);
if (socket_session_data[socket.id].close_me) socket.end();
socket_buffer[socket.id] = null;
});
socket.on('error', (err) => {
socket.end();
});
socket.on('end', function () {
cleanupSocket(socket);
});
}
var z_title = "zefie's wtv minisrv v" + require('./package.json').version;
console.log("**** Welcome to " + z_title + " ****");
console.log(" *** Reading service configuration...");
try {
var services_configured = JSON.parse(fs.readFileSync(__dirname + "/services.json"));
} catch (e) {
throw("ERROR: Could not read services.json", e);
}
var service_ip = services_configured.config.service_ip;
Object.keys(services_configured.services).forEach(function (k) {
services_configured.services[k].name = k;
if (!services_configured.services[k].host) {
services_configured.services[k].host = service_ip;
}
if (services_configured.services[k].port) {
ports.push(services_configured.services[k].port);
}
services_configured.services[k].toString = function () {
var outstr = "wtv-service: name=" + this.name + " host=" + this.host + " port=" + this.port;
if (this.flags) outstr += " flags=" + this.flags;
if (this.connections) outstr += " flags=" + this.connections;
if (k == "wtv-star") {
outstr += "\nwtv-service: name=wtv-* host=" + this.host + " port=" + this.port;
if (this.flags) outstr += " flags=" + this.flags;
if (this.connections) outstr += " flags=" + this.connections;
}
return outstr;
}
console.log(" * Configured Service", k, "on port", services_configured.services[k].port);
})
var initstring = '';
ports.sort();
// de-duplicate ports in case user configured multiple services on same port
const bind_ports = [...new Set(ports)]
bind_ports.forEach(function (v) {
try {
var server = net.createServer(handleSocket);
server.listen(v, '0.0.0.0');
initstring += v + ", ";
} catch (e) {
throw ("Could not bind to port", v, e.toString());
}
});
initstring = initstring.substring(0, initstring.length - 2);
server.listen(port, '0.0.0.0');
process.stdout.write("Looking up public IP address... ");
//pubip = getPublicIP();
console.log(pubip + " ...");
console.log(" * Started server on ports " + initstring + "... Service IP is " + service_ip);
console.log('Listening on port ' + port + ' for WebTV Units in Scriptless Mode');

View File

@@ -28,12 +28,59 @@
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Content Include=".gitignore" />
<Content Include="app.js" />
<Content Include="services.json">
<SubType>Code</SubType>
</Content>
<Content Include="ServiceVault\wtv-flashrom\get-lc2-page.js" />
<Content Include="ServiceVault\wtv-flashrom\lc2-download-failed.html" />
<Content Include="ServiceVault\wtv-flashrom\lc2-download-failed.js" />
<Content Include="ServiceVault\wtv-flashrom\willie.js" />
<Content Include="ServiceVault\wtv-star\images\HackTVLogo.gif" />
<Content Include="ServiceVault\wtv-star\images\HackTVLogoJewel.gif" />
<Content Include="ServiceVault\wtv-star\images\WebTVLogoJewel.gif" />
<Content Include="ServiceVault\wtv-tricks\blastcache.txt" />
<Content Include="ServiceVault\wtv-tricks\go-offline.js" />
<Content Include="ServiceVault\wtv-update\content\diskmaps\htvupdate.txt" />
<Content Include="ServiceVault\wtv-update\content\htvupdate\Games\cSetup.html" />
<Content Include="ServiceVault\wtv-update\content\htvupdate\Games\Games.html" />
<Content Include="ServiceVault\wtv-update\content\htvupdate\MattMan\Tricks\tricks.html" />
<Content Include="ServiceVault\wtv-update\sync.js">
<SubType>Code</SubType>
</Content>
<Content Include="ServiceVault\wtv-update\update.html" />
<Content Include="ServiceVault\wtv-home\home.js" />
<Content Include="ServiceVault\wtv-update\updatesuccess.txt" />
<Content Include="ServiceVault\wtv-1800\finish-prereg.js" />
<Content Include="ServiceVault\wtv-1800\preregister.js" />
<Content Include="ServiceVault\wtv-head-waiter\finalize-security.js" />
<Content Include="ServiceVault\wtv-head-waiter\login-stage-two.js" />
<Content Include="ServiceVault\wtv-head-waiter\login.js" />
<Content Include="ServiceVault\wtv-home\splash.txt" />
<Content Include="ServiceVault\wtv-log\log.js" />
<Content Include="wtvsec.js">
<SubType>Code</SubType>
</Content>
<Content Include="package.json" />
<Content Include="README.md" />
</ItemGroup>
<ItemGroup>
<Folder Include="ServiceVault\" />
<Folder Include="ServiceVault\wtv-flashrom\" />
<Folder Include="ServiceVault\wtv-star\" />
<Folder Include="ServiceVault\wtv-star\images\" />
<Folder Include="ServiceVault\wtv-tricks\" />
<Folder Include="ServiceVault\wtv-update\" />
<Folder Include="ServiceVault\wtv-1800\" />
<Folder Include="ServiceVault\wtv-head-waiter\" />
<Folder Include="ServiceVault\wtv-home\" />
<Folder Include="ServiceVault\wtv-log\" />
<Folder Include="ServiceVault\wtv-update\content\" />
<Folder Include="ServiceVault\wtv-update\content\diskmaps\" />
<Folder Include="ServiceVault\wtv-update\content\htvupdate\" />
<Folder Include="ServiceVault\wtv-update\content\htvupdate\Games\" />
<Folder Include="ServiceVault\wtv-update\content\htvupdate\MattMan\" />
<Folder Include="ServiceVault\wtv-update\content\htvupdate\MattMan\Tricks\" />
</ItemGroup>
<Import Project="$(VSToolsPath)\Node.js Tools\Microsoft.NodejsToolsV2.targets" />
</Project>

View File

@@ -1,26 +1,23 @@
{
"name": "hacktv_updsrv",
"version": "0.0.0",
"version": "0.5.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"arc4": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/arc4/-/arc4-3.4.0.tgz",
"integrity": "sha512-zFQmSbTwSTrICYV8kldrD3YreCtlLIKEZk+lmlNSlpUKU/cF9o746WFEy9eNqLrqSyUgAAjB3gnD9UXdK23beA==",
"requires": {
"lodash": "4.17.4"
}
"buffer-factory": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/buffer-factory/-/buffer-factory-1.0.8.tgz",
"integrity": "sha512-EkUcaWsg7Vw+bfpGrpqzDIV4u3FksbHy0I0x9IZogqtCh9rZ5IHPTs/1QtZNNm/8BOeznUKTXIA72sVXEmFREQ=="
},
"crypto-js": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.0.0.tgz",
"integrity": "sha512-bzHZN8Pn+gS7DQA6n+iUmBfl0hO5DJq++QP3U6uTucDtk/0iGpXd/Gg7CGR0p8tJhofJyaKoWBuJI4eAO00BBg=="
},
"lodash": {
"version": "4.17.4",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz",
"integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4="
"endianness": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/endianness/-/endianness-8.0.2.tgz",
"integrity": "sha512-IU+77+jJ7lpw2qZ3NUuqBZFy3GuioNgXUdsL1L9tooDNTaw0TgOnwNuc+8Ns+haDaTifK97QLzmOANJtI/rGvw=="
},
"mime-db": {
"version": "1.48.0",
@@ -35,6 +32,20 @@
"mime-db": "1.48.0"
}
},
"node-addon-api": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.0.0.tgz",
"integrity": "sha512-sSHCgWfJ+Lui/u+0msF3oyCgvdkhxDbkCS6Q8uiJquzOimkJBvX6hl5aSSA7DR1XbMpdM8r7phjcF63sF4rkKg=="
},
"node-crc16": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/node-crc16/-/node-crc16-2.0.7.tgz",
"integrity": "sha512-dbLudH39wvydMXsT5E/jdyEP0t/kO3EOFQawVeBk3cJP23+jL4feoCWF2kMThEvijrEt2isFx2XzYjLkf0h8+g==",
"requires": {
"buffer-factory": "1.0.8",
"node-addon-api": "3.0.0"
}
},
"strftime": {
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/strftime/-/strftime-0.10.0.tgz",

View File

@@ -1,15 +1,16 @@
{
"name": "hacktv_updsrv",
"version": "0.0.0",
"version": "0.6.1",
"description": "hacktv_updsrv",
"main": "app.js",
"author": {
"name": ""
},
"dependencies": {
"arc4": "^3.4.0",
"crypto-js": "^4.0.0",
"endianness": "^8.0.2",
"mime-types": "^2.1.31",
"node-crc16": "^2.0.7",
"strftime": "^0.10.0"
}
}

View File

@@ -0,0 +1,47 @@
{
"config": {
"service_ip": "192.168.11.8"
},
"services": {
"wtv-1800": {
"port": 1615,
"connections": 1
},
"wtv-star": {
"port": 1603,
"flags": "0x00000007"
},
"wtv-head-waiter": {
"port": 1601,
"flags": "0x00000001",
"connections": 1
},
"wtv-update": {
"port": 1619,
"flags": "0x04",
"connections": 3
},
"wtv-log": {
"port": 1609,
"connections": 1
},
"wtv-home": {
"port": 1612,
"flags": "0x00000010"
},
"wtv-tricks": {
"port": 1602,
"flags": "0x00000004"
},
"wtv-flashrom": {
"port": 1618,
"flags": "0x00000040"
},
"wtv-music": {
"port": 1656,
"flags": "0x04",
"connections": 3
}
}
}

View File

@@ -1,60 +1,77 @@
const CryptoJS = require('crypto-js');
const rc4 = require('arc4');
const endianness = require('endianness');
var crypto = require('crypto');
class WTVNetworkSecurity {
class WTVSec {
//initial_shared_key = CryptoJS.lib.WordArray.random(8);
initial_shared_key_b64 = "CC5rWmRUE0o="; // You can change this but it doesn't mean much for security. Just make sure its static. 8 bytes base64 encoded.
initial_shared_key = null;
current_shared_key = null;
challenge_key = null;
challenge_signed_key = null;
challenge_raw = null;
challenge_response = null;
challenge_b64 = null;
ticket_b64 = null;
incarnation = 1;
incarnation = 0;
session_key1 = null;
session_key2 = null;
hRC4_Key1 = null;
hRC4_Key2 = null;
RC4Session = new Array();
zdebug = false;
constructor(wtv_initial_key = CryptoJS.lib.WordArray.random(8), wtv_incarnation = 1) {
var initial_key = wtv_initial_key;
constructor(wtv_incarnation = 1) {
this.zdebug = true;
this.initial_shared_key = CryptoJS.enc.Base64.parse(this.initial_shared_key_b64);
if (initial_key.sigBytes === 8) {
if (this.initial_shared_key.sigBytes === 8) {
this.incarnation = wtv_incarnation;
this.initial_shared_key = initial_key;
this.current_shared_key = initial_key;
this.current_shared_key = this.initial_shared_key;
} else {
throw ("Invalid initial key length");
}
}
set_incarnation(wtv_incarnation) {
this.incarnation = wtv_incarnation;
if (this.incarnation != wtv_incarnation) {
this.incarnation = wtv_incarnation;
this.SecureOn();
}
}
increment_incarnation() {
this.incarnation = this.incarnation + 1;
this.set_incarnation(parseInt(this.incarnation) + 1);
}
DuplicateWordArray(wa) {
return CryptoJS.lib.WordArray.create(this.wordArrayToUint8Array(wa).buffer);
}
PrepareTicket() {
// store last challenge response in ticket
var ticket_data = this.challenge_response;
var ticket_data = this.challenge_raw;
try {
var ticket_data_enc = CryptoJS.DES.encrypt(ticket_data, this.current_shared_key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.NoPadding
});
this.ticket_b64 = this.current_shared_key.concat(ticket_data_enc.ciphertext.toString(CryptoJS.enc.Base64));
// create a copy of WordArray since concat modifies the original
var current_shared_key = this.DuplicateWordArray(this.current_shared_key);
var challenge_signed_key = this.DuplicateWordArray(this.challenge_signed_key);
this.ticket_b64 = current_shared_key.concat(challenge_signed_key.concat(ticket_data_enc.ciphertext)).toString(CryptoJS.enc.Base64);
} catch (e) {
console.log("Error encrypting ticket: " + e.toString());
return null;
}
return this.ticket_b64;
}
DecodeTicket(ticket_b64) {
var ticket_hex = CryptoJS.enc.Base64.parse(ticket_b64);
var ticket_key = CryptoJS.enc.Hex.parse(ticket_hex.substring(0, this.current_shared_key.sigBytes));
var ticket_hex = CryptoJS.enc.Base64.parse(ticket_b64).toString(CryptoJS.enc.Hex);
var ticket_key = CryptoJS.enc.Hex.parse(ticket_hex.substring(0,16));
var challenge_key = CryptoJS.enc.Hex.parse(ticket_hex.substring(16, 32));
var challenge_enc = CryptoJS.enc.Hex.parse(ticket_hex.substring(32));
var ticket_dec = CryptoJS.DES.decrypt(
{
ciphertext: challenge_enc
@@ -62,38 +79,39 @@ class WTVNetworkSecurity {
ticket_key,
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
padding: CryptoJS.pad.NoPadding
}
);
this.ProcessChallenge(ticket_dec);
this.ProcessChallenge(ticket_dec.toString(CryptoJS.enc.Base64), challenge_key);
console.log(" * Decoded session from wtv-ticket");
}
ProcessChallenge(wtv_challenge) {
ProcessChallenge(wtv_challenge, key = this.current_shared_key) {
var challenge_raw = CryptoJS.enc.Base64.parse(wtv_challenge);
if (challenge_raw.sigBytes > 8) {
var challenge_raw_hex = challenge_raw.toString(CryptoJS.enc.Hex);
var challenge_id_hex = challenge_raw_hex.substring(0, (8 * 2));
var challenge_enc_hex = challenge_raw_hex.substring((8*2));
var challenge_enc = CryptoJS.enc.Hex.parse(challenge_enc_hex);
var challenge_decrypted = CryptoJS.DES.decrypt(
{
ciphertext: challenge_enc
},
this.current_shared_key,
key,
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.ZeroPadding
padding: CryptoJS.pad.NoPadding
}
);
var challenge_dec_hex = challenge_decrypted.toString(CryptoJS.enc.Hex);
var challenge_md5_challenge = CryptoJS.MD5(CryptoJS.enc.Hex.parse(challenge_dec_hex.substring(0, (80 * 2))));
if (challenge_dec_hex.substring((80 * 2), (96 * 2)) == challenge_md5_challenge.toString(CryptoJS.enc.Hex)) {
var test = challenge_dec_hex.substring((80 * 2), (96 * 2));
var test2 = challenge_md5_challenge.toString(CryptoJS.enc.Hex);
if (test == test2) {
this.current_shared_key = CryptoJS.enc.Hex.parse(challenge_dec_hex.substring((72*2), (80*2)));
var challenge_echo = CryptoJS.enc.Hex.parse(challenge_dec_hex.substr(0, (40*2)));
@@ -101,15 +119,15 @@ class WTVNetworkSecurity {
this.session_key1 = CryptoJS.enc.Hex.parse(challenge_dec_hex.substring((40*2), (56*2)));
this.session_key2 = CryptoJS.enc.Hex.parse(challenge_dec_hex.substring((56*2), (72*2)));
var echo_encrypted = CryptoJS.DES.encrypt(CryptoJS.MD5(challenge_echo).concat(challenge_echo), this.current_shared_key, {
var echo_encrypted = CryptoJS.DES.encrypt(CryptoJS.MD5(challenge_echo).concat(challenge_echo).concat(CryptoJS.enc.Utf8.parse("\x08".repeat(8))), this.current_shared_key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.NoPadding
});
// Last bytes is just extra padding
var challenge_response = CryptoJS.enc.Hex.parse(challenge_raw_hex.substr(0, (8 * 2))).concat(echo_encrypted.ciphertext.concat(CryptoJS.enc.Utf8.parse("\x00".repeat(8))));
this.challenge_raw = challenge_raw;
this.challenge_key = this.current_shared_key;
var challenge_response = CryptoJS.enc.Hex.parse(challenge_raw_hex.substr(0, (8 * 2))).concat(echo_encrypted.ciphertext);
return challenge_response;
} else {
throw ("Couldn't solve challenge");
@@ -133,16 +151,19 @@ class WTVNetworkSecurity {
*/
var random_id_question_mark = CryptoJS.lib.WordArray.random(8);
var challenge_id = CryptoJS.lib.WordArray.random(8);
var echo_me = CryptoJS.lib.WordArray.random(40);
this.session_key1 = CryptoJS.lib.WordArray.random(16);
this.session_key2 = CryptoJS.lib.WordArray.random(16);
var new_shared_key = CryptoJS.lib.WordArray.random(8);
var challenge_puzzle = echo_me.concat(this.session_key1.concat(this.session_key2.concat(new_shared_key)));
var challenge_secret = challenge_puzzle.concat(CryptoJS.MD5(challenge_puzzle).concat(CryptoJS.enc.Hex.parse("\x00".repeat(8))));
var session_key1 = this.DuplicateWordArray(this.session_key1);
var session_key2 = this.DuplicateWordArray(this.session_key2);
var challenge_puzzle = echo_me.concat(session_key1.concat(session_key2.concat(new_shared_key)));
var challenge_secret = challenge_puzzle.concat(CryptoJS.MD5(challenge_puzzle).concat(CryptoJS.enc.Hex.parse("\x08".repeat(8))));
// Shhhh!!
var challenge_secreted = CryptoJS.DES.encrypt(challenge_secret, this.current_shared_key, {
mode: CryptoJS.mode.ECB,
@@ -150,64 +171,119 @@ class WTVNetworkSecurity {
});
var challenge = random_id_question_mark.concat(challenge_secreted.ciphertext);
var challenge = challenge_id.concat(challenge_secreted.ciphertext);
var challenge_b64 = challenge.toString(CryptoJS.enc.Base64);
// get the expected response for when client sends it
this.challenge_signed_key = this.current_shared_key;
this.challenge_response = this.ProcessChallenge(challenge_b64);
this.challenge_key = this.current_shared_key;
this.challenge_b64 = challenge_b64;
this.current_shared_key = new_shared_key;
return challenge_b64;
}
SecureOn() {
var buf = Buffer.allocUnsafe(4);
buf.writeUIntLE(this.incarnation, 0, 4);
var bigbuf = buf.readUIntBE(0, 4);
var md5_digest_key1 = CryptoJS.MD5(this.session_key1.concat(CryptoJS.lib.WordArray.create(bigbuf).concat(this.session_key1)));
wordToByteArray(word, length) {
var ba = [],
i,
xFF = 0xFF;
if (length > 0)
ba.push(word >>> 24);
if (length > 1)
ba.push((word >>> 16) & xFF);
if (length > 2)
ba.push((word >>> 8) & xFF);
if (length > 3)
ba.push(word & xFF);
buf = Buffer.allocUnsafe(4);
buf.writeUIntLE(this.incarnation, 0, 4);
bigbuf = buf.readUIntBE(0, 4);
var md5_digest_key2 = CryptoJS.MD5(this.session_key2.concat(CryptoJS.lib.WordArray.create(bigbuf).concat(this.session_key2)));
this.hRC4_Key1 = md5_digest_key1;
this.hRC4_Key2 = md5_digest_key2;
return ba;
}
EncryptKey1(data) {
return this.Encrypt(this.hRC4_Key1, data);
wordArrayToUint8Array(wordArray, length = 0) {
if (wordArray.hasOwnProperty("sigBytes") && wordArray.hasOwnProperty("words")) {
length = wordArray.sigBytes;
wordArray = wordArray.words;
}
var result = [],
bytes,
i = 0;
while (length > 0) {
bytes = this.wordToByteArray(wordArray[i], Math.min(4, length));
length -= bytes.length;
result.push(bytes);
i++;
}
return new Uint8Array([].concat.apply([], result));
}
EncryptKey2(data) {
return this.Encrypt(this.hRC4_Key2, data);
}
Encrypt(context, data) {
if (key != null) {
return CryptoJS.RC4.encrypt(data, key);
} else {
throw ("Invalid RC4 encryption key");
SecureOn(rc4session = null) {
if (this.zdebug) console.log(" # Generating RC4 sessions with wtv-incarnation: " + this.incarnation);
var buf = new Uint8Array([0xff & this.incarnation, 0xff & (this.incarnation >> 8), 0xff & (this.incarnation >> 16), 0xff & (this.incarnation >> 24)]);
endianness(buf, 4);
this.hRC4_Key1 = CryptoJS.MD5(this.DuplicateWordArray(this.session_key1).concat(CryptoJS.lib.WordArray.create(buf).concat(this.DuplicateWordArray(this.session_key1))));
this.hRC4_Key2 = CryptoJS.MD5(this.DuplicateWordArray(this.session_key2).concat(CryptoJS.lib.WordArray.create(buf).concat(this.DuplicateWordArray(this.session_key2))));
switch (rc4session) {
case 0:
this.RC4Session[0] = crypto.createCipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key1)),'');
break;
case 1:
this.RC4Session[1] = crypto.createDecipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key1)),'');
break;
case 2:
this.RC4Session[2] = crypto.createCipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key2)),'');
break;
case 3:
this.RC4Session[3] = crypto.createDecipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key2)),'');
break;
default:
this.RC4Session[0] = crypto.createCipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key1)), '');
this.RC4Session[1] = crypto.createDecipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key1)), '');
this.RC4Session[2] = crypto.createCipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key2)), '');
this.RC4Session[3] = crypto.createDecipheriv('rc4', Buffer.from(this.wordArrayToUint8Array(this.hRC4_Key2)), '');
break;
}
}
DecryptKey1(data) {
return this.Decrypt(this.hRC4_Key1, data);
NewRC4Session(num) {
this.SecureOn(num);
}
DecryptKey2(data) {
return this.Decrypt(this.hRC4_Key2, data);
}
Decrypt(key, data) {
if (key != null) {
return CryptoJS.RC4.decrypt(data, key);
} else {
throw ("Invalid RC4 encryption key");
Encrypt(keynum, data) {
var session_id;
switch (keynum) {
case 0:
session_id = 0;
break;
case 1:
session_id = 2
break;
default:
throw ("Invalid key option (0 or 1 only)");
break;
}
if (!this.RC4Session[session_id]) {
this.NewRC4Session(session_id);
}
return this.RC4Session[session_id].update(Buffer.from(this.wordArrayToUint8Array(data)));
}
Decrypt(keynum, data) {
var session_id;
switch (keynum) {
case 0:
session_id = 1;
break;
case 1:
session_id = 3;
break;
default:
throw ("Invalid key option (0 or 1 only)");
break;
}
if (!this.RC4Session[session_id]) {
this.NewRC4Session(session_id);
}
return this.RC4Session[session_id].update(Buffer.from(this.wordArrayToUint8Array(data)));
}
Test() {
@@ -221,4 +297,4 @@ class WTVNetworkSecurity {
}
}
module.exports = WTVNetworkSecurity;
module.exports = WTVSec;