Skip to content

Commit 2c5d41b

Browse files
Peter XiePeter Xie
authored andcommitted
mistake header
1 parent 0977914 commit 2c5d41b

File tree

12 files changed

+189
-177
lines changed

12 files changed

+189
-177
lines changed

app/compress.ts

Lines changed: 44 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@
1515
* limitations under the License.
1616
*/
1717

18-
import * as crypto from 'crypto'
18+
import * as Crypto from 'crypto'
1919
import * as Async from 'async'
2020
import * as Stream from 'stream'
2121
import * as Net from 'net'
22+
import HttpHeader from './httpProxy'
2223
const EOF = Buffer.from ( '\r\n\r\n', 'utf8' )
2324
import * as fs from 'fs'
2425
export interface packetBuffer {
@@ -36,20 +37,20 @@ export interface pairConnect {
3637
export const encrypt = ( text: Buffer, masterkey: string, CallBack ) => {
3738
let salt = null
3839
Async.waterfall ([
39-
next => crypto.randomBytes ( 64, next ),
40+
next => Crypto.randomBytes ( 64, next ),
4041
( _salt, next ) => {
4142
salt = _salt
42-
crypto.pbkdf2 ( masterkey, salt, 2145, 32, 'sha512', next )
43+
Crypto.pbkdf2 ( masterkey, salt, 2145, 32, 'sha512', next )
4344
}
4445
], ( err, derivedKey ) => {
4546
if ( err )
4647
return CallBack ( err )
4748

48-
crypto.randomBytes ( 12, ( err1, iv ) => {
49+
Crypto.randomBytes ( 12, ( err1, iv ) => {
4950
if ( err1 )
5051
return CallBack ( err1 )
5152

52-
const cipher = crypto.createCipheriv ( 'aes-256-gcm', derivedKey, iv );
53+
const cipher = Crypto.createCipheriv ( 'aes-256-gcm', derivedKey, iv );
5354

5455
let _text = Buffer.concat ([ Buffer.alloc ( 4, 0 ) , text ])
5556
_text.writeUInt32BE ( text.length, 0 )
@@ -82,13 +83,13 @@ export const decrypt = ( data: Buffer, masterkey, CallBack ) => {
8283
const tag = data.slice ( 76, 92 );
8384
const text = data.slice ( 92 );
8485
// derive key using; 32 byte key length
85-
crypto.pbkdf2 ( masterkey, salt , 2145, 32, 'sha512', ( err, derivedKey ) => {
86+
Crypto.pbkdf2 ( masterkey, salt , 2145, 32, 'sha512', ( err, derivedKey ) => {
8687

8788
if ( err )
8889
return CallBack ( err )
8990
// AES 256 GCM Mode
9091
try {
91-
const decipher = crypto.createDecipheriv ( 'aes-256-gcm', derivedKey, iv )
92+
const decipher = Crypto.createDecipheriv ( 'aes-256-gcm', derivedKey, iv )
9293
decipher.setAuthTag ( tag )
9394
const decrypted = Buffer.concat([decipher.update ( text ), decipher.final ( )])
9495
const leng = decrypted.slice( 4, 4 + decrypted.readUInt32BE(0))
@@ -134,6 +135,27 @@ const HTTP_HEADER = Buffer.from (
134135
`HTTP/1.1 200 OK\r\nDate: ${ new Date ().toUTCString ()}\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: keep-alive\r\nVary: Accept-Encoding\r\n\r\n`, 'utf8')
135136
const HTTP_EOF = Buffer.from ( '\r\n\r\n', 'utf8' )
136137

138+
const getHeaderString = ( headers, host: string, port: number ) => {
139+
//console.trace (`getHeaderString header[${ !headers ? 'null': Object.keys ( headers ).forEach ( n => { return `${ n }: [${ + headers [ n ]}] ` }) }]`)
140+
const ret = `Host: ${ host }${ port !== 80 ? ':' + port : '' }\r\n` +
141+
( headers && headers['accept'] ? headers['accept'] : 'Accept: */*') + '\r\n' +
142+
( headers && headers['accept-language'] ? headers['accept-language'] : 'Accept-Language: en-ca' ) + '\r\n' +
143+
( headers && headers['connection'] ? headers['Connection'] : 'Connection: keep-alive' ) + '\r\n' +
144+
( headers && headers['accept-encoding'] ? headers['accept-encoding'] : 'Accept-Encoding: gzip, deflate' ) + '\r\n' +
145+
( headers && headers['user-agent'] ? headers[ 'user-agent'] : 'User-Agent: Mozilla/5.0' ) + '\r\n'
146+
return ret
147+
}
148+
149+
export const otherRequestForNet = ( path: string, host: string, port: number, headers: HttpHeader ) => {
150+
151+
if ( path.length < 2048 )
152+
return `GET /${ path } HTTP/1.1\r\n` + getHeaderString ( headers && headers.headers ? headers: null, host, port ) + '\r\n'
153+
154+
return `POST /${ Crypto.randomBytes ( 4 + Math.random () * 100 ).toString ('base64') } HTTP/1.1\r\n` +
155+
getHeaderString ( headers && headers.headers ? headers.headers: null, host, port ) + `Content-Length: ${ path.length }\r\n\r\n` + path + '\r\n\r\n'
156+
}
157+
158+
137159
export class encryptStream extends Stream.Transform {
138160
private salt: Buffer
139161
private iv: Buffer
@@ -143,16 +165,17 @@ export class encryptStream extends Stream.Transform {
143165
private BlockBuffer ( _buf: Buffer ) {
144166
return Buffer.from( _buf.length.toString( 16 ).toUpperCase() + '\r\n', 'utf8' )
145167
}
168+
146169
private init ( callback ) {
147170
return Async.waterfall ([
148-
next => crypto.randomBytes ( 64, next ),
171+
next => Crypto.randomBytes ( 64, next ),
149172
( _salt, next ) => {
150173
this.salt = _salt
151-
crypto.randomBytes ( 12, next )
174+
Crypto.randomBytes ( 12, next )
152175
},
153176
( _iv, next ) => {
154177
this.iv = _iv
155-
crypto.pbkdf2 ( this.password, this.salt, 2145, 32, 'sha512', next )
178+
Crypto.pbkdf2 ( this.password, this.salt, 2145, 32, 'sha512', next )
156179
}
157180
], ( err, derivedKey ) => {
158181

@@ -161,8 +184,10 @@ export class encryptStream extends Stream.Transform {
161184
})
162185
}
163186

164-
constructor ( private password: string, private random: number, private httpHeader : ( str: string ) => Buffer ) {
187+
constructor ( private password: string, private random: number, private host: string, private port: number, private httpRequest: HttpHeader ) {
188+
165189
super ()
190+
console.trace (`new encryptStream get httpRequest [${ httpRequest && httpRequest.headers ? JSON.stringify ( httpRequest.headers ): 'null'}]`)
166191
}
167192

168193
public _transform ( chunk: Buffer, encode, cb ) {
@@ -171,7 +196,7 @@ export class encryptStream extends Stream.Transform {
171196
return this._transform ( chunk, encode, cb )
172197
})
173198
}
174-
const cipher = crypto.createCipheriv ( 'aes-256-gcm', this.derivedKey, this.iv )
199+
const cipher = Crypto.createCipheriv ( 'aes-256-gcm', this.derivedKey, this.iv )
175200

176201
let _text = Buffer.concat ([ Buffer.alloc ( 4, 0 ) , chunk ])
177202

@@ -186,22 +211,13 @@ export class encryptStream extends Stream.Transform {
186211
if ( this.first ) {
187212
this.first = false
188213
const black = Buffer.concat ([ this.salt, this.iv, _buf1 ]).toString ( 'base64' )
189-
if ( ! this.httpHeader ) {
190-
const _buf4 = Buffer.from ( black, 'base64')
191-
return cb ( null, Buffer.concat ([ HTTP_HEADER, this.BlockBuffer ( _buf4 ), _buf4, EOF ]))
192-
}
193-
const _buf2 = this.httpHeader ( black )
194-
195-
return cb ( null, _buf2 )
214+
215+
otherRequestForNet ( black, this.host, this.port, this.httpRequest )
216+
return cb ( null, otherRequestForNet ( black, this.host, this.port, this.httpRequest ))
196217
}
197218

198-
const _buf2 = _buf1.toString( 'base64' )
199-
200-
if ( this.httpHeader ) {
201-
return cb ( null, this.httpHeader ( _buf2 ))
202-
}
203-
const _buf3 = Buffer.from ( _buf2, 'base64' )
204-
return cb ( null, Buffer.concat ([ this.BlockBuffer ( _buf3 ), _buf3, EOF ]))
219+
const _buf2 = _buf1.toString ( 'base64' )
220+
return cb ( null, otherRequestForNet ( _buf2, this.host, this.port, this.httpRequest ))
205221
}
206222
}
207223

@@ -213,7 +229,7 @@ export class decryptStream extends Stream.Transform {
213229
private derivedKey: Buffer = null
214230
private _decrypt ( _text: Buffer ) {
215231

216-
const decipher = crypto.createDecipheriv ( 'aes-256-gcm', this.derivedKey, this.iv )
232+
const decipher = Crypto.createDecipheriv ( 'aes-256-gcm', this.derivedKey, this.iv )
217233
decipher.setAuthTag ( _text.slice ( 0, 16 ))
218234
try {
219235
const _buf = Buffer.concat ([ decipher.update ( _text.slice ( 16 )), decipher.final () ])
@@ -233,7 +249,7 @@ export class decryptStream extends Stream.Transform {
233249
public _First ( chunk: Buffer, CallBack: ( err?: Error, text?: Buffer ) => void ) {
234250
this.salt = chunk.slice ( 0, 64 );
235251
this.iv = chunk.slice ( 64, 76 );
236-
return crypto.pbkdf2 ( this.password, this.salt , 2145, 32, 'sha512', ( err, derivedKey ) => {
252+
return Crypto.pbkdf2 ( this.password, this.salt , 2145, 32, 'sha512', ( err, derivedKey ) => {
237253
if ( err ) {
238254
console.log ( `decryptStream crypto.pbkdf2 ERROR: ${ err.message }` )
239255
return CallBack ( err )

app/gateway.ts

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,12 @@ import * as Dns from 'dns'
2020
import * as Net from 'net'
2121
import * as res from './res'
2222
import * as Stream from 'stream'
23+
import * as Crypto from 'crypto'
24+
import { homedir } from 'os'
25+
import HttpHeader from './httpProxy'
2326

2427
const Day = 1000 * 60 * 60 * 24
2528

26-
const otherRequestForNet = ( path: string, host: string, port: number, UserAgent: string ) => {
27-
if ( path.length < 2048)
28-
return `GET /${ path } HTTP/1.1\r\n` +
29-
`Host: ${ host }:${ port }\r\n` +
30-
`Accept: */*\r\n` +
31-
`Accept-Language: en-ca\r\n` +
32-
`Connection: keep-alive\r\n` +
33-
`Accept-Encoding: gzip, deflate\r\n` +
34-
`User-Agent: ${ UserAgent ? UserAgent : 'Mozilla/5.0' }\r\n\r\n`
35-
return `POST /${ Buffer.allocUnsafe ( 10 + Math.random()).toString('base64') } HTTP/1.1\r\n` +
36-
`Host: ${ host }:${ port }\r\n` +
37-
`Content-Length: ${ path.length }\r\n\r\n` +
38-
path + '\r\n\r\n'
39-
}
40-
4129
class hostLookupResponse extends Stream.Writable {
4230
constructor ( private CallBack: ( err?: Error, dns?: domainData ) => void ) { super ()}
4331
public _write ( chunk: Buffer, enc, next ) {
@@ -59,24 +47,18 @@ class hostLookupResponse extends Stream.Writable {
5947
}
6048

6149
export default class gateWay {
62-
63-
private userAgent = null
6450

65-
private request ( str: string ) {
66-
return Buffer.from ( otherRequestForNet ( str, this.serverIp, this.serverPort, this.userAgent ), 'utf8' )
67-
}
51+
private httpHeader: HttpHeader = null
6852

6953
constructor ( public serverIp: string, public serverPort: number, private password: string ) {
7054
}
7155

72-
public hostLookup ( hostName: string, userAgent: string, CallBack: ( err?: Error, hostIp?: domainData ) => void ) {
56+
public hostLookup ( hostName: string, CallBack: ( err?: Error, hostIp?: domainData ) => void ) {
7357

7458

7559
const _data = new Buffer ( JSON.stringify ({ hostName: hostName }), 'utf8' )
7660

77-
const encrypt = new Compress.encryptStream ( this.password, 0, ( str: string ) => {
78-
return this.request ( str )
79-
})
61+
const encrypt = new Compress.encryptStream ( this.password, 1 + Math.random() * 1000, this.serverIp, this.serverPort, this.httpHeader )
8062

8163
const finish = new hostLookupResponse ( CallBack )
8264
const httpBlock = new Compress.getDecryptClientStreamFromHttp ()
@@ -104,12 +86,12 @@ export default class gateWay {
10486

10587
}
10688

107-
public requestGetWay ( id: string, uuuu: VE_IPptpStream, userAgent: string, socket: Net.Socket ) {
108-
this.userAgent = userAgent
89+
public requestGetWay ( id: string, uuuu: VE_IPptpStream, httpHeader: HttpHeader, socket: Net.Socket ) {
90+
if ( httpHeader )
91+
this.httpHeader = httpHeader
92+
console.trace ( 'requestGetWay',JSON.stringify ( this.httpHeader.headers ))
10993
const decrypt = new Compress.decryptStream ( this.password )
110-
const encrypt = new Compress.encryptStream ( this.password, 0, ( str: string ) => {
111-
return this.request ( str )
112-
})
94+
const encrypt = new Compress.encryptStream ( this.password, 0, this.serverIp, this.serverPort, this.httpHeader )
11395
const httpBlock = new Compress.getDecryptClientStreamFromHttp ()
11496
httpBlock.once ( 'error', err => {
11597
socket.end ( res._HTTP_404 )
@@ -123,14 +105,12 @@ export default class gateWay {
123105
}
124106

125107
public requestGetWayTest ( id: string, uuuu: VE_IPptpStream, userAgent: string, socket: Net.Socket ) {
126-
console.log ('connect to test port!')
108+
console.log ( 'connect to test port!' )
127109
const _socket = Net.createConnection ({ port: this.serverPort + 1, host: this.serverIp })
128110

129111
_socket.on ( 'connect', () => {
130-
const ls = new Compress.printStream ('>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
131-
const ls1 = new Compress.printStream ('<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
132112
_socket.pipe ( socket ).pipe ( _socket )
133-
const _buf = Buffer.from ( otherRequestForNet ( Buffer.from ( JSON.stringify ( uuuu ), 'utf8' ).toString ( 'base64' ), this.serverIp, this.serverPort, this.userAgent ), 'utf8' )
113+
const _buf = Buffer.from ( Compress.otherRequestForNet ( Buffer.from ( JSON.stringify ( uuuu ), 'utf8' ).toString ( 'base64' ), this.serverIp, this.serverPort, this.httpHeader ), 'utf8' )
134114
_socket.write ( _buf )
135115

136116
})

app/proxyServer.ts

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import * as Net from 'net'
2020
import * as Http from 'http'
2121
import * as Dns from 'dns'
22-
import HttpProxyHeader from './httpProxy'
22+
import HttpHeader from './httpProxy'
2323
import * as Async from 'async'
2424
import * as Compress from './compress'
2525
import * as util from 'util'
@@ -32,7 +32,8 @@ import * as Path from 'path'
3232
import * as Socks from './socket5ForiOpn'
3333
import gateWay from './gateway'
3434
import * as Os from 'os'
35-
const { remote } = require ( "electron" )
35+
36+
const { remote } = require ( 'electron' )
3637

3738
const whiteIpFile = 'whiteIpList.json'
3839
Http.globalAgent.maxSockets = 1024
@@ -99,7 +100,7 @@ const otherRespon = ( path: string, host: string, port: number, UserAgent: strin
99100

100101
const testLogin = ( req: Buffer, loginUserList: string ) => {
101102

102-
const header = new HttpProxyHeader ( req )
103+
const header = new HttpHeader ( req )
103104
if ( header.isGet && header.Url.path === loginUserList )
104105
return true
105106

@@ -255,13 +256,13 @@ export const tryConnectHost = ( hostname: string, hostIp: domainData, port: numb
255256

256257
}
257258

258-
export const isAllBlackedByFireWall = ( hostName: string, ip6: boolean, gatway: gateWay, userAgent: string, domainListPool: Map < string, domainData >,
259+
export const isAllBlackedByFireWall = ( hostName: string, ip6: boolean, gatway: gateWay, httpHead: HttpHeader, domainListPool: Map < string, domainData >,
259260
CallBack: ( err?: Error, hostIp?: domainData ) => void ) => {
260261

261262
const hostIp = domainListPool.get ( hostName )
262263
const now = new Date ().getTime ()
263264
if ( ! hostIp || hostIp.expire < now )
264-
return gatway.hostLookup ( hostName, userAgent, ( err, ipadd ) => {
265+
return gatway.hostLookup ( hostName, ( err, ipadd ) => {
265266
return CallBack ( err, ipadd )
266267
})
267268
return CallBack ( null, hostIp )
@@ -276,9 +277,8 @@ const isSslFromBuffer = ( buffer ) => {
276277
const httpProxy = ( clientSocket: Net.Socket, buffer: Buffer, useGatWay: boolean, ip6: boolean, connectTimeOut: number,
277278
domainListPool: Map < string, domainData >, gatway: gateWay, checkAgainTime: number, blackDomainList: string[] ) => {
278279

279-
const httpHead = new HttpProxyHeader ( buffer )
280+
const httpHead = new HttpHeader ( buffer )
280281
const hostName = httpHead.Url.hostname
281-
const userAgent = httpHead.headers [ 'user-agent' ]
282282

283283
const CallBack = ( err?: Error, _data?: Buffer ) => {
284284

@@ -296,7 +296,7 @@ const httpProxy = ( clientSocket: Net.Socket, buffer: Buffer, useGatWay: boolean
296296
}
297297

298298
const id = `[${ clientSocket.remoteAddress.split(':')[3] }:${ clientSocket.remotePort }][${ uuuu.uuid }] `
299-
return gatway.requestGetWay ( id, uuuu, userAgent, clientSocket )
299+
return gatway.requestGetWay ( id, uuuu, httpHead, clientSocket )
300300

301301
}
302302

@@ -318,7 +318,7 @@ const httpProxy = ( clientSocket: Net.Socket, buffer: Buffer, useGatWay: boolean
318318

319319
if ( ! hostIp ) {
320320

321-
return isAllBlackedByFireWall ( hostName, ip6, gatway, userAgent, domainListPool, ( err, _hostIp ) => {
321+
return isAllBlackedByFireWall ( hostName, ip6, gatway, null, domainListPool, ( err, _hostIp ) => {
322322
if ( err ) {
323323
console.log ( `[${ hostName }] Blocked!`)
324324
return closeClientSocket ( clientSocket, 504, null )
@@ -375,7 +375,7 @@ const getPac = ( hostIp: string, port: number, http: boolean, sock5: boolean ) =
375375

376376

377377
export class proxyServer {
378-
public UdpServer = new Socks.UdpDgram ()
378+
//public UdpServer = new Socks.UdpDgram ()
379379
private hostLocalIpv4: { network: string, address: string } []= []
380380
private hostLocalIpv6: string = null
381381
private hostGlobalIpV4: string = null
@@ -397,7 +397,7 @@ export class proxyServer {
397397
return
398398
this.getGlobalIpRunning = true
399399

400-
gateWay.hostLookup ( testGatewayDomainName, null, ( err, data ) => {
400+
gateWay.hostLookup ( testGatewayDomainName, ( err, data ) => {
401401
if ( err )
402402
return console.log ( 'getGlobalIp ERROR:', err.message )
403403
console.log ( data )
@@ -427,31 +427,30 @@ export class proxyServer {
427427
public connectHostTimeOut: number, public useGatWay: boolean, public domainBlackList: string[] ) {
428428
this.getGlobalIp ( this.gateway )
429429
let socks = null
430+
let httpHead: HttpHeader = null
430431
const server = Net.createServer ( socket => {
431432
const ip = socket.remoteAddress
432433
const isWhiteIp = this.whiteIpList.find ( n => { return n === ip }) ? true : false
433-
let agent = 'Mozilla/5.0'
434-
console.log (`new socket!`)
434+
435435
socket.once ( 'data', ( data: Buffer ) => {
436436
const dataStr = data.toString()
437437
if ( /^GET \/pac/.test ( dataStr )) {
438-
const httpHead = new HttpProxyHeader ( data )
439-
agent = httpHead.headers['user-agent']
440-
const sock5 = /Windows NT|Darwin/i.test ( agent ) && ! /CFNetwork/i.test (agent)
441-
438+
httpHead = new HttpHeader ( data )
439+
const agent = httpHead.headers [ 'user-agent']
440+
441+
const sock5 = /Windows NT|Darwin/i.test ( agent ) && ! /CFNetwork/i.test ( agent )
442+
console.log (`new GET /pac\n headers[${ JSON.stringify ( httpHead.headers )}]\n sock5=[${ sock5 }]\n`)
442443
let ret = getPac ( this.localProxyServerIP, this.port, false, sock5 )
443444
if ( /pacHttp/.test( dataStr ))
444445
ret = getPac ( this.localProxyServerIP, this.port, true, sock5 )
445-
console.log ( `/GET \/pac from :[${ socket.remoteAddress }] sock5 [${ sock5 }] agent [${ agent }] httpHead.headers [${ Object.keys(httpHead.headers)}]`)
446-
console.log ( dataStr )
447446
return socket.end ( ret )
448447
}
449-
448+
console.log (`new socket!\n headers [${ httpHead && httpHead.headers ? JSON.stringify ( httpHead.headers) : 'null' }]`, )
450449
switch ( data.readUInt8 ( 0 )) {
451450
case 0x4:
452-
return socks = new Socks.sockt4 ( socket, data, agent, this )
451+
return socks = new Socks.sockt4 ( socket, data, httpHead, this )
453452
case 0x5:
454-
return socks = new Socks.socks5 ( socket, agent, this )
453+
return socks = new Socks.socks5 ( socket, httpHead, this )
455454
default:
456455
return httpProxy ( socket, data, useGatWay, this.hostGlobalIpV6 ? true : false, connectHostTimeOut, domainListPool, this.gateway, checkAgainTimeOut, domainBlackList )
457456
}

0 commit comments

Comments
 (0)