From 2465bdfe84883db1772180275760bd945183f278 Mon Sep 17 00:00:00 2001 From: Kyle Graehl Date: Mon, 27 Jan 2020 19:15:57 -0800 Subject: [PATCH 01/11] add makedeps --- makedeps/README.md | 1 + makedeps/index.js | 15 +++++++++++++++ makedeps/package.json | 17 +++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 makedeps/README.md create mode 100644 makedeps/index.js create mode 100644 makedeps/package.json diff --git a/makedeps/README.md b/makedeps/README.md new file mode 100644 index 00000000..f62a5826 --- /dev/null +++ b/makedeps/README.md @@ -0,0 +1 @@ +run `yarn make` or `npm run make` to build the dependency bundle for the main app \ No newline at end of file diff --git a/makedeps/index.js b/makedeps/index.js new file mode 100644 index 00000000..465360fc --- /dev/null +++ b/makedeps/index.js @@ -0,0 +1,15 @@ +var m + +m = require('react') +window.React = m + +m = require('react-dom') +window.ReactDOM = m + +m = require('@material-ui/core') +window.MaterialUI = m + +m = require('underscore') +window._ = m + +module.exports = {} diff --git a/makedeps/package.json b/makedeps/package.json new file mode 100644 index 00000000..0698e433 --- /dev/null +++ b/makedeps/package.json @@ -0,0 +1,17 @@ +{ + "name": "makedeps", + "version": "1.0.0", + "main": "index.js", + "license": "MIT", + "scripts": { + "make": "./node_modules/.bin/browserify index.js > ../assets/bundle.js" + }, + "dependencies": { + "@material-ui/core": "^4.6.1", + "@material-ui/icons": "^4.5.1", + "browserify": "^16.5.0", + "react": "^16.12.0", + "react-dom": "^16.12.0", + "underscore": "^1.9.1" + } +} From c6e9056e5f03b51621dfc608fd283d6850083d5d Mon Sep 17 00:00:00 2001 From: Kyle Graehl Date: Wed, 11 Mar 2020 21:45:11 -0700 Subject: [PATCH 02/11] forgot babelrc --- react-ui/.babelrc | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 react-ui/.babelrc diff --git a/react-ui/.babelrc b/react-ui/.babelrc new file mode 100644 index 00000000..59566c26 --- /dev/null +++ b/react-ui/.babelrc @@ -0,0 +1,6 @@ +{ + "plugins": [ + ["@babel/plugin-transform-react-jsx",{useBuiltIns:true}], + "@babel/plugin-syntax-class-properties" + ] +} From e65842440daf2662cf6e7df34caf64102da51ed8 Mon Sep 17 00:00:00 2001 From: Kyle Graehl Date: Fri, 17 Jul 2020 17:37:14 +0200 Subject: [PATCH 03/11] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c08b92b9..d99bf345 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ handlers is an array of 2 element arrays where the first item is a regular expre ``` cd web-server-chrome +mkdir assets cd makedeps npm install npm run make # this builds the app dependencies such as react and material-ui into a bundle From 26523114dc0fc9683e30e042603f33e9ff119668 Mon Sep 17 00:00:00 2001 From: Kyle Graehl Date: Thu, 30 Jul 2020 21:44:14 +0200 Subject: [PATCH 04/11] forgot babelrc --- chromise.js | 183 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 chromise.js diff --git a/chromise.js b/chromise.js new file mode 100644 index 00000000..4b7b1694 --- /dev/null +++ b/chromise.js @@ -0,0 +1,183 @@ +/** + * @author Alexey Kuzmin + * @fileoverview Promise based wrapper for Chrome Extension API. + * @see https://developer.chrome.com/extensions/api_index + * @license MIT + * @version 3.1.0 + */ + + + +;(function(global) { + 'use strict'; + + let apiProxy = { + /** + * @param {!Object} apiObject + * @param {string} methodName + * @param {Arguments} callArguments Arguments to be passes to method call. + */ + callMethod(apiObject, methodName, callArguments) { + let originalMethod = apiObject[methodName]; + let callArgumentsArray = Array.from(callArguments); + + return new Promise((resolve, reject) => { + let callback = apiProxy.processResponse_.bind(null, resolve, reject); + callArgumentsArray.push(callback); + originalMethod.apply(apiObject, callArgumentsArray); + }); + }, + + /** + * @param {!Function} callback + * @param {!Function} errback + * @param {!Array} response Response from Extension API. + * @private + */ + processResponse_(callback, errback, ...response) { + let error = global.chrome.runtime.lastError; + if (typeof error == 'object') { + errback(new Error(error.message)); + return; + } + + if (response.length < 2) + response = response[0]; // undefined if response is empty + + callback(response); + } + }; + + + let classifier = { + /** + * @param {string} letter + * @return {boolean} + * @private + */ + isCapitalLetter_(letter) { + return letter == letter.toUpperCase(); + }, + + /** + * @param {string} string + * @return {boolean} + * @private + */ + startsWithCapitalLetter_(string) { + return classifier.isCapitalLetter_(string[0]); + }, + + /** + * We need to decide should given property be wrapped or not + * by its name only. Retrieving its value would cause API initialization, + * that can take a long time (dozens of ms). + * @param {string} propName + * @return {boolean} + */ + propertyNeedsWrapping(propName) { + if (classifier.startsWithCapitalLetter_(propName)) { + // Either constructor, enum, or constant. + return false; + } + + if (propName.startsWith('on') && + classifier.isCapitalLetter_(propName[2])) { + // Extension API event, e.g. 'onUpdated'. + return false; + } + + // Must be a namespace or a method. + return true; + } + }; + + + let wrapGuy = { + /** + * @param {!Object} api API object to wrap. + * @return {!Object} + */ + wrapApi(api) { + return wrapGuy.wrapObject_(api); + }, + + /** + * Wraps API object. + * @param {!Object} apiObject + * @return {!Object} + * @private + */ + wrapObject_(apiObject) { + let wrappedObject = {}; + + Object.keys(apiObject) + .filter(classifier.propertyNeedsWrapping) + .forEach(keyName => { + Object.defineProperty(wrappedObject, keyName, { + enumerable: true, + configurable: true, + get() { + return wrapGuy.wrapObjectField_(apiObject, keyName); + } + }); + }); + + return wrappedObject; + }, + + /** + * @type {!Map} + * @private + */ + wrappedFieldsCache_: new Map(), + + /** + * Wraps single object field. + * @param {!Object} apiObject + * @param {string} keyName + * @return {?|undefined} + * @private + */ + wrapObjectField_(apiObject, keyName) { + let apiEntry = apiObject[keyName]; + + if (wrapGuy.wrappedFieldsCache_.has(apiEntry)) { + return wrapGuy.wrappedFieldsCache_.get(apiEntry); + } + + let entryType = typeof apiEntry; + let wrappedField; + if (entryType == 'function') { + wrappedField = wrapGuy.wrapMethod_(apiObject, keyName); + } + if (entryType == 'object') { + wrappedField = wrapGuy.wrapObject_(apiEntry); + } + + if (wrappedField) { + wrapGuy.wrappedFieldsCache_.set(apiEntry, wrappedField); + return wrappedField; + } + }, + + /** + * Wraps API method. + * @param {!Object} apiObject + * @param {string} methodName + * @return {!Function} + * @private + */ + wrapMethod_(apiObject, methodName) { + return function() { + return apiProxy.callMethod(apiObject, methodName, arguments); + } + } + }; + + + let chromise = wrapGuy.wrapApi(global.chrome); + + global.chromise = chromise; + +}(this)); From 6f156d77ee35ac57570189ac5159feca09f889a9 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Thu, 1 Apr 2021 14:54:53 +0200 Subject: [PATCH 05/11] Made https work, altough very unpolished yet --- common.js | 7 +- makedeps/index.js | 3 + makedeps/package.json | 3 + manifest.json | 2 +- minimize.sh | 2 +- socket.js | 427 ++++++++++++++++++++++++++++++++++++++++++ stream.js | 158 +++++++++++++++- webapp.js | 27 ++- 8 files changed, 607 insertions(+), 22 deletions(-) create mode 100644 socket.js diff --git a/common.js b/common.js index a65a4a53..3af74507 100644 --- a/common.js +++ b/common.js @@ -205,11 +205,12 @@ function ui82arr(arr, startOffset) { return outarr } function str2ab(s) { - var arr = [] + var buf = new ArrayBuffer(s.length); + var bufView = new Uint8Array(buf); for (var i=0; i ../assets/bundle.js" }, "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.13.12", "@material-ui/core": "^4.6.1", "@material-ui/icons": "^4.5.1", + "babel": "^6.23.0", "browserify": "^16.5.0", + "node-forge": "^0.8.0", "react": "^16.12.0", "react-dom": "^16.12.0", "underscore": "^1.9.1" diff --git a/manifest.json b/manifest.json index a55664f4..ebe55e16 100644 --- a/manifest.json +++ b/manifest.json @@ -10,7 +10,7 @@ "minimum_chrome_version": "45", "app": { "background": { - "scripts": ["underscore.js","encoding.js","common.js","log-full.js","mime.js","buffer.js","request.js","stream.js","chromesocketxhr.js","connection.js","webapp.js","websocket.js","handlers.js","httplib.js","upnp.js","background.js"] + "scripts": ["underscore.js","encoding.js","common.js", "assets/bundle.js", "log-full.js","mime.js","buffer.js","request.js","socket.js","stream.js","chromesocketxhr.js","connection.js","webapp.js","websocket.js","handlers.js","httplib.js","upnp.js","background.js"] } }, "permissions": [ diff --git a/minimize.sh b/minimize.sh index 25e50b17..902be54b 100644 --- a/minimize.sh +++ b/minimize.sh @@ -1 +1 @@ -cat "underscore.js" "encoding.js" "common.js" "log-full.js" "mime.js" "buffer.js" "request.js" "stream.js" "chromesocketxhr.js" "connection.js" "webapp.js" "websocket.js" "upnp.js" "handlers.js" "httplib.js" > wsc-chrome.min.js +cat "underscore.js" "encoding.js" "common.js" "log-full.js" "mime.js" "buffer.js" "request.js" "socket.js" "stream.js" "chromesocketxhr.js" "connection.js" "webapp.js" "websocket.js" "upnp.js" "handlers.js" "httplib.js" > wsc-chrome.min.js diff --git a/socket.js b/socket.js new file mode 100644 index 00000000..8aa7d148 --- /dev/null +++ b/socket.js @@ -0,0 +1,427 @@ +(function() { + + +// function to create certificate +var createCert = function(cn, data) { + console.log( + 'Generating 1024-bit key-pair and certificate for \"' + cn + '\".'); + var keys = forge.pki.rsa.generateKeyPair(1024); + console.log('key-pair created.'); + + var cert = forge.pki.createCertificate(); + cert.serialNumber = '01'; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + cert.validity.notAfter.setFullYear( + cert.validity.notBefore.getFullYear() + 1); + var attrs = [{ + name: 'commonName', + value: cn + }, { + name: 'countryName', + value: 'SE' + }, { + shortName: 'ST', + value: 'Kronoberg' + }, { + name: 'localityName', + value: 'Växjö' + }, { + name: 'organizationName', + value: 'Test' + }, { + shortName: 'OU', + value: 'Test' + }]; + cert.setSubject(attrs); + cert.setIssuer(attrs); + cert.setExtensions([{ + name: 'basicConstraints', + cA: true + }, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true + }, { + name: 'subjectAltName', + altNames: [{ + type: 6, // URI + value: 'http://localhost' + }] + }]); + // FIXME: add subjectKeyIdentifier extension + // FIXME: add authorityKeyIdentifier extension + cert.publicKey = keys.publicKey; + + // self-sign certificate + cert.sign(keys.privateKey); + + // save data + data[cn] = { + cert: forge.pki.certificateToPem(cert), + privateKey: forge.pki.privateKeyToPem(keys.privateKey) + }; + + console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); +}; + +var end = {}; +var data = {}; + +// create certificate for server and client +createCert('server', data); +//createCert('client', data); +console.log(data.server.privateKey); +console.log(data.server.cert); + +/* +var success = false; + +// create TLS client +end.client = forge.tls.createConnection({ + server: false, + caStore: [data.server.cert], + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + virtualHost: 'server', + verify: function(c, verified, depth, certs) { + console.log( + 'TLS Client verifying certificate w/CN: \"' + + certs[0].subject.getField('CN').value + + '\", verified: ' + verified + '...'); + return verified; + }, + connected: function(c) { + console.log('Client connected...'); + + // send message to server + setTimeout(function() { + c.prepareHeartbeatRequest('heartbeat'); + c.prepare('Hello Server'); + }, 1); + }, + getCertificate: function(c, hint) { + console.log('Client getting certificate ...'); + return data.client.cert; + }, + getPrivateKey: function(c, cert) { + return data.client.privateKey; + }, + tlsDataReady: function(c) { + // send TLS data to server + end.server.process(c.tlsData.getBytes()); + }, + dataReady: function(c) { + var response = c.data.getBytes(); + console.log('Client received \"' + response + '\"'); + success = (response === 'Hello Client'); + c.close(); + }, + heartbeatReceived: function(c, payload) { + console.log('Client received heartbeat: ' + payload.getBytes()); + }, + closed: function(c) { + console.log('Client disconnected.'); + if(success) { + console.log('PASS'); + } else { + console.log('FAIL'); + } + }, + error: function(c, error) { + console.log('Client error: ' + error.message); + } +}); + +// create TLS server +end.server = forge.tls.createConnection({ + server: true, + caStore: [data.client.cert], + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + connected: function(c) { + console.log('Server connected'); + c.prepareHeartbeatRequest('heartbeat'); + }, + verifyClient: true, + verify: function(c, verified, depth, certs) { + console.log( + 'Server verifying certificate w/CN: \"' + + certs[0].subject.getField('CN').value + + '\", verified: ' + verified + '...'); + return verified; + }, + getCertificate: function(c, hint) { + console.log('Server getting certificate for \"' + hint[0] + '\"...'); + return data.server.cert; + }, + getPrivateKey: function(c, cert) { + return data.server.privateKey; + }, + tlsDataReady: function(c) { + // send TLS data to client + end.client.process(c.tlsData.getBytes()); + }, + dataReady: function(c) { + console.log('Server received \"' + c.data.getBytes() + '\"'); + + // send response + c.prepare('Hello Client'); + c.close(); + }, + heartbeatReceived: function(c, payload) { + console.log('Server received heartbeat: ' + payload.getBytes()); + }, + closed: function(c) { + console.log('Server disconnected.'); + }, + error: function(c, error) { + console.log('Server error: ' + error.message); + } +}); + +//console.log('created TLS client and server, doing handshake...'); +//end.client.handshake(); + +//WSC.Tls = {end: end, data: data }; +*/ + + + + + // the Ssl sockets + var string2ArrayBuffer = function(string, callback) { + var buf = new ArrayBuffer(string.length); + var bufView = new Uint8Array(buf); + for (var i=0; i < string.length; i++) { + bufView[i] = string.charCodeAt(i); + } + callback(buf); + }; + + var arrayBuffer2String = function(buf, callback) { + var bufView = new Uint8Array(buf); + var chunkSize = 65536; + var result = ''; + for (var i = 0; i < bufView.length; i += chunkSize) { + result += String.fromCharCode.apply(null, bufView.subarray(i, Math.min(i + chunkSize, bufView.length))); + } + callback(result); + }; + + var SocketSslTcp = function() { + this._buffer = ''; + this._requiredBytes = 0; + this._onReceive = this._onReceive.bind(this); + this._onReceiveError = this._onReceiveError.bind(this); + //chrome.sockets.tcp.apply(this); //net.AbstractTCPSocket.apply(this); + }; + + //SocketSslTcp.prototype.__proto__ = net.AbstractTCPSocket.prototype; + SocketSslTcp.prototype = Object.create(chrome.sockets.tcp, {constructor: {value: SocketSslTcp}}) + +/* // implementation in webapp.js + SocketSslTcp.prototype.connect = function(addr, port) { + var _this = this; + this._active(); + chrome.sockets.tcp.create({}, function(si) { + _this.socketId = si.socketId; + if (_this.socketId > 0) { + registerSocketConnection(si.socketId); + chrome.sockets.tcp.setPaused(_this.socketId, true); + // Port will be of the form +port# given that it is using SSL. + chrome.sockets.tcp.connect(_this.socketId, addr, parseInt(port.substr(1)), + _this._onConnect.bind(_this)); + } else { + _this.emit('error', "Couldn\'t create socket"); + } + }); + };*/ + + SocketSslTcp.prototype._onConnect = function(rc) { + if (rc < 0) { + this.emit('error', 'Couldn\'t connect to socket: ' + + chrome.runtime.lastError.message + ' (error ' + (-rc) + ')'); + return; + } + this._initializeTls({}); + this._tls.handshake(this._tlsOptions.sessionId || null); + chrome.sockets.tcp.onReceive.addListener(this._onReceive); + chrome.sockets.tcp.onReceiveError.addListener(this._onReceiveError); + chrome.sockets.tcp.setPaused(this.socketId, false); + }; + + SocketSslTcp.prototype._initializeTls = function(options) { + var _this = this; + this._tlsOptions = options; + this._tls = window.forge.tls.createConnection({ + server: false, + sessionId: options.sessionId || null, + caStore: options.caStore || [], + sessionCache: options.sessionCache || null, + cipherSuites: options.cipherSuites || [ + window.forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + window.forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + virtualHost: options.virtualHost, + verify: options.verify || function() { return true }, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature, + deflate: options.deflate, + inflate: options.inflate, + connected: function(c) { + // first handshake complete, call handler +// if(c.handshakes === 1) { + console.log('TLS socket connected'); + _this.emit('connect'); +// } + }, + tlsDataReady: function(c) { + // send TLS data over socket + var bytes = c.tlsData.getBytes(); + string2ArrayBuffer(bytes, function(data) { + chrome.sockets.tcp.send(_this.socketId, data, function(sendInfo) { + if (sendInfo.resultCode < 0) { + console.error('SOCKET ERROR on write: ' + + chrome.runtime.lastError.message + ' (error ' + (-sendInfo.resultCode) + ')'); + } + if (sendInfo.bytesSent === data.byteLength) { + _this.emit('drain'); + } else { + if (sendInfo.bytesSent >= 0) { + console.error('Can\'t handle non-complete writes: wrote ' + + sendInfo.bytesSent + ' expected ' + data.byteLength); + } + _this.emit('error', 'Invalid write on socket, code: ' + sendInfo.resultCode); + } + }); + }); + }, + dataReady: function(c) { + // indicate application data is ready + var data = c.data.getBytes(); + irc.util.toSocketData(forge.util.decodeUtf8(data), function(data) { + _this.emit('data', data); + }); + }, + closed: function(c) { + // close socket + _this._close(); + }, + error: function(c, e) { + // send error, close socket + _this.emit('error', 'tlsError: ' + e.message); + _this._close(); + } + }); + }; + + SocketSslTcp.prototype._onClosed = function() { + if (this._tls && this._tls.open && this._tls.handshaking) { + this.emit('error', 'Connection closed during handshake'); + } + }; + + SocketSslTcp.prototype.close = function() { + if (this._tls) + this._tls.close(); + }; + + SocketSslTcp.prototype._close = function() { + if (this.socketId != null) { + chrome.sockets.tcp.onReceive.removeListener(this._onReceive); + chrome.sockets.tcp.onReceiveError.removeListener(this._onReceiveError); + chrome.sockets.tcp.disconnect(this.socketId); + chrome.sockets.tcp.close(this.socketId); + registerSocketConnection(this.socketId, true); + } + this.emit('close'); + }; + + SocketSslTcp.prototype.write = function(data) { + var _this = this; + arrayBuffer2String(data, function(data) { + _this._tls.prepare(data); + }); + }; + + SocketSslTcp.prototype._onReceive = function(receiveInfo) { + if (receiveInfo.socketId != this.socketId) + return; + this._active(); + if (!this._tls.open) + return; + var _this = this; + arrayBuffer2String(receiveInfo.data, function (data) { + _this._buffer += data; + if (_this._buffer.length >= _this._requiredBytes) { + _this._requiredBytes = _this._tls.process(_this._buffer); + _this._buffer = ''; + } + }); + }; + + SocketSslTcp.prototype._onReceiveError = function (readInfo) { + if (readInfo.socketId != this.socketId) + return; + this._active(); + if (info.resultCode === -100) { // connection closed + this.emit('end'); + this._close(); + } + else { + var message = ''; + if (chrome.runtime.lastError) + message = chrome.runtime.lastError.message; + this.emit('error', 'read from socket: ' + message + ' (error ' + + (-readInfo.resultCode) + ')'); + this._close(); + return; + } + }; + + + // wrapper for socket.tcp + var SocketTcp = function() { } + SocketTcp.prototype = Object.create(chrome.sockets.tcp, {constructor: {value: SocketTcp}}); + SocketTcp.prototype.onReceive = { + addListener:function(cb) { + chrome.sockets.tcp.onReceive.addListener(function(){ + console.log("SocketTcp.onReceive", arguments); + cb.apply(this, arguments); + }); + } + } + + + + var SocketsSingleton = function() { } + SocketsSingleton.prototype = Object.create(chrome.sockets, {constructor: {value: SocketsSingleton}}); + SocketsSingleton.prototype.setSsl = function(useSsl) { + if (!useSsl) { + SocketsSingleton.prototype.tcp = new SocketTcp; //chrome.sockets.tcp; + SocketsSingleton.prototype.udp = chrome.sockets.udp; + SocketsSingleton.prototype.tcpServer = chrome.sockets.tcpServer; + } else { + console.warn("Not ready yet"); + SocketsSingleton.prototype.tcp = new SocketSslTcp; //chrome.sockets.tcp; + SocketsSingleton.prototype.udp = chrome.sockets.udp; + SocketsSingleton.prototype.tcpServer = chrome.sockets.tcpServer; + } + } + + WSC.Sockets = new SocketsSingleton; + WSC.Sockets.setSsl(true); + + +})(); + diff --git a/stream.js b/stream.js index 03ff0478..83a0b79d 100644 --- a/stream.js +++ b/stream.js @@ -1,5 +1,40 @@ (function() { + const serverCert = +'-----BEGIN CERTIFICATE-----\ +MIICcDCCAdmgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQ8wDQYDVQQDEwZzZXJ2\ +ZXIxCzAJBgNVBAYTAlNFMRIwEAYDVQQIEwlLcm9ub2JlcmcxDjAMBgNVBAcTBVbk\ +eGr2MQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MB4XDTIxMDQwMTExMzU0\ +NloXDTIyMDQwMTExMzU0NlowYDEPMA0GA1UEAxMGc2VydmVyMQswCQYDVQQGEwJT\ +RTESMBAGA1UECBMJS3Jvbm9iZXJnMQ4wDAYDVQQHEwVW5Hhq9jENMAsGA1UEChME\ +VGVzdDENMAsGA1UECxMEVGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\ +kojUsq1rKK2lm5XjRKHBPcbWPZxIIvWqwTTYEyi8ds8fYpovqiYFg9Jhp+maK8wx\ +t/xXEx10hkZIG6Bhbj80DXWm+CeNxxuZJnQw4eg68DCpFgRNFXtz+U3GtCgZYjQ4\ +E8iUMcRqIJK7OGJslfhVCEfsBs64/bO9V45jBMWyQDMCAwEAAaM6MDgwDAYDVR0T\ +BAUwAwEB/zALBgNVHQ8EBAMCAvQwGwYDVR0RBBQwEoYQaHR0cDovL2xvY2FsaG9z\ +dDANBgkqhkiG9w0BAQUFAAOBgQBnO8VP6AKmWi0MmVOBWvg45dfUN6OVWGZATJ5k\ +1t0P/OboXCBxBu/H2PxIA7k43eSJOwJOTsmfEiRk27Kys2FXy1uhIUKCyIHs49xE\ +Xa+HWyUgHX+/V0sKdPbnQu5dF9+vlpX087114qRv6ynrBbVh8e9eYuLSoXnRHvmk\ +WvUyJA==\ +-----END CERTIFICATE-----'; + + const privateKey = +'-----BEGIN RSA PRIVATE KEY-----\ +MIICXgIBAAKBgQCSiNSyrWsoraWbleNEocE9xtY9nEgi9arBNNgTKLx2zx9imi+q\ +JgWD0mGn6ZorzDG3/FcTHXSGRkgboGFuPzQNdab4J43HG5kmdDDh6DrwMKkWBE0V\ +e3P5Tca0KBliNDgTyJQxxGogkrs4YmyV+FUIR+wGzrj9s71XjmMExbJAMwIDAQAB\ +AoGAFEp0QYW4B/r7qq63uMI5UweclQ12A7lG+tgJb6W9aypFK080eHgpXVadhTXY\ +zmXJILQFjrUOdKV4yLKNq0l/OIQrUXOjs0ulIyN71WBReZmeT/5uTi9/b9IOThiw\ +2Nl8mc8zHxChkNtb231Js9NA2XW9/ivOu1nXph6qvxvzB/kCQQDN/blSMWaYFIfW\ +cGs+Z/W3ZOps5A7y1EhAqd3X6RgGIvsaRTyhi6TUr8zx+L0v/yKpReI1xVErkH+H\ +BZ12bDHfAkEAthvmJPagriiM4hqYrfmgpwY7wz06KZGiZYujpjqSKTCB74fKvphe\ +jDwkPBctBFiVvgiC72qSbAzpdAf2tNoELQJBALBlOqJY7WsEAcKvKBcbvT3b7Cdt\ +MCPfhzPggrmWwNzYbcD0U1RfGbqMBOucvp1wVQUxc+Hp43Vz2tEMDOhRBG8CQQCS\ +KGwbKJInlUYVRlFZ+Gq3Auq+NQrUSB11sJBEnuemBVeT3oGbXQEtPiu6ysMHpO1x\ +2rTz4K3p6KcJyEZ6Oix1AkEAjAOWXdP3Kv0hFPB6PVKTZRKeQYDzT6gzEmXMmwpT\ +bKvn7lSUQKst5Br8W/BiEs15HtRZIxIzlIqWzAodxMZghw==\ +-----END RSA PRIVATE KEY-----'; + var peerSockMap = {} WSC.peerSockMap = peerSockMap @@ -13,7 +48,6 @@ chrome.sockets.tcp.onReceive.addListener( onTCPReceive ) chrome.sockets.tcp.onReceiveError.addListener( onTCPReceive ) - var sockets = chrome.sockets function IOStream(sockId) { this.sockId = sockId peerSockMap[this.sockId] = this @@ -94,12 +128,17 @@ var data = this.writeBuffer.consume_any_max(4096) //console.log(this.sockId,'tcp.send',data.byteLength) //console.log(this.sockId,'tcp.send',WSC.ui82str(new Uint8Array(data))) - sockets.tcp.send( this.sockId, data, this.onWrite.bind(this, callback) ) + this._writeToTcp(data, this.onWrite.bind(this, callback)); }, write: function(data) { this.writeBuffer.add(data) this.tryWrite() }, + // may be overridden by StreamTls + _writeToTcp: function(data, cb) { + chrome.sockets.tcp.send( this.sockId, data, cb); + }, + onWrite: function(callback, evt) { var err = chrome.runtime.lastError if (err) { @@ -145,11 +184,15 @@ this.log('remote killed connection',evt.resultCode) this.error({message:'error code',errno:evt.resultCode}) } else { - this.readBuffer.add(evt.data) - if (this.onread) { this.onread() } - this.checkBuffer() + this._fillReadBuffer(evt.data) } }, + // specialized so IOStreamTls can subclass + _fillReadBuffer: function(data) { + this.readBuffer.add(data); + if (this.onread) { this.onread() } + this.checkBuffer() + }, log: function(msg,msg2,msg3) { if (WSC.VERBOSE) { console.log(this.sockId,msg,msg2,msg3) @@ -185,7 +228,7 @@ this.runCloseCallbacks() //console.log('tcp sock close',this.sockId) delete peerSockMap[this.sockId] - sockets.tcp.close(this.sockId, this.onClosed.bind(this,reason)) + chrome.sockets.tcp.close(this.sockId, this.onClosed.bind(this,reason)) //this.sockId = null this.cleanup() }, @@ -219,13 +262,114 @@ return } console.log(this.sockId,'tryClose') - sockets.tcp.send(this.sockId, new ArrayBuffer, callback) + chrome.sockets.tcp.send(this.sockId, new ArrayBuffer, callback) }, cleanup: function() { this.writeBuffer = new WSC.Buffer } } + + var arrayBuffer2String = function(buf) { + var bufView = new Uint8Array(buf); + var chunkSize = 65536; + var result = ''; + for (var i = 0; i < bufView.length; i += chunkSize) { + result += String.fromCharCode.apply(null, bufView.subarray(i, Math.min(i + chunkSize, bufView.length))); + } + return result; + } + + + var IOStreamTls = function(sockId) { + this.writeCallbacks = []; + this.readCallbacks = []; + var _t = this; + + this.tlsServer = forge.tls.createConnection({ + server: true, + //caStore: [WSC.Tls.data.client.cert], + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + connected: function(c) { + console.log('Server connected'); + //c.prepareHeartbeatRequest('heartbeat'); + }, + verifyClient: false, +// verify: function(c, verified, depth, certs) { +// console.log( +// 'Server verifying certificate w/CN: \"' + +// certs[0].subject.getField('CN').value + +// '\", verified: ' + verified + '...'); +// return verified; +// }, + getCertificate: function(c, hint) { + console.log('Server getting certificate for \"' + hint[0] + '\"...'); + return serverCert; //WSC.Tls.data.server.cert; + }, + getPrivateKey: function(c, cert) { + console.log('Server getting privateKey for \"' + cert + '\"...'); + return privateKey;//WSC.Tls.data.server.privateKey; + + + }, + tlsDataReady: function(c) { + // send TLS data to client + //end.client.process(c.tlsData.getBytes()); + var cb = _t.writeCallbacks.pop() || function(){}; // || function(){_t.error(c.tlsData);} + let str = c.tlsData.getBytes(); + var b = WSC.str2ab(str); + console.log('encrypt to client: ' + str); + if (this.connected) + chrome.sockets.tcp.send( _t.sockId, b, cb); + else + _t.error("tlsData on closed socket"); + }, + dataReady: function(c) { + // decrypted data from client + let str = c.data.getBytes(); + console.log('client sent \"' + str + '\"'); + _t.readBuffer.add(WSC.str2ab(str)); + if (_t.onread) { _t.onread() } + _t.checkBuffer() + + // send response + //c.prepare('Hello Client'); + //c.close(); + }, + heartbeatReceived: function(c, payload) { + console.log('Server received heartbeat: ' + payload.getBytes()); + }, + closed: function(c) { + console.log('Server disconnected.'); + }, + error: function(c, error) { + console.log(error.origin + ' error: ' + error.message + ' at level:' + error.alert.level + ' desc:' + error.alert.description); + } + }); + + IOStream.apply(this, arguments); + } + IOStreamTls.prototype = { + _writeToTcp: function(data, cb) { + let str = WSC.arrayBufferToString(data); + console.log('send to client: ' + str); + this.writeCallbacks.push(cb); + this.tlsServer.prepare(str); + }, + _fillReadBuffer: function(data) { + let str = arrayBuffer2String(data); + let n = this.tlsServer.process(str); + console.log('from client: ' + str); + } + }; + IOStreamTls.prototype.__proto__ = IOStream.prototype; //; = Object.create(chrome.sockets.tcp, {constructor: {value: IOStream}}) + + WSC.IOStreamTls = IOStreamTls; + WSC.IOStream = IOStream; })(); diff --git a/webapp.js b/webapp.js index 3d1e72c0..86d6b962 100644 --- a/webapp.js +++ b/webapp.js @@ -1,5 +1,4 @@ (function(){ - var sockets = chrome.sockets function WebApplication(opts) { // need to support creating multiple WebApplication... @@ -7,6 +6,7 @@ console.log('initialize webapp with opts',opts) } opts = opts || {} + opts.optUseTls = true; /// FIXME hack this into a gui selectable thing this.id = Math.random().toString() this.opts = opts this.handlers = opts.handlers || [] @@ -348,7 +348,7 @@ return this.port + i*3 + Math.pow(i,2)*2 }, tryListenOnPort: function(state, callback) { - sockets.tcpServer.getSockets( function(sockets) { + chrome.sockets.tcpServer.getSockets( function(sockets) { if (sockets.length == 0) { this.doTryListenOnPort(state, callback) } else { @@ -367,15 +367,15 @@ }, doTryListenOnPort: function(state, callback) { var opts = this.opts.optBackground ? {name:"WSCListenSocket", persistent:true} : {} - sockets.tcpServer.create(opts, this.onServerSocket.bind(this,state,callback)) + chrome.sockets.tcpServer.create(opts, this.onServerSocket.bind(this,state,callback)) }, onServerSocket: function(state,callback,sockInfo) { var host = this.get_host() this.sockInfo = sockInfo var tryPort = this.computePortRetry(state.port_attempts) - state.port_attempts++ - //console.log('attempting to listen on port',host,tryPort) - sockets.tcpServer.listen(this.sockInfo.socketId, + state.port_attempts++; + console.log('attempting to listen on port',host,tryPort) + chrome.sockets.tcpServer.listen(this.sockInfo.socketId, host, tryPort, function(result) { @@ -461,8 +461,8 @@ } }, bindAcceptCallbacks: function() { - sockets.tcpServer.onAcceptError.addListener(this.onAcceptError.bind(this)) - sockets.tcpServer.onAccept.addListener(this.onAccept.bind(this)) + chrome.sockets.tcpServer.onAcceptError.addListener(this.onAcceptError.bind(this)) + chrome.sockets.tcpServer.onAccept.addListener(this.onAccept.bind(this)) }, onAcceptError: function(acceptInfo) { if (acceptInfo.socketId != this.sockInfo.socketId) { return } @@ -474,7 +474,13 @@ //console.log('onAccept',acceptInfo,this.sockInfo) if (acceptInfo.socketId != this.sockInfo.socketId) { return } if (acceptInfo.socketId) { - var stream = new WSC.IOStream(acceptInfo.clientSocketId) + let stream; + if (this.opts.optUseTls) { + //this._initializeTls(); + //this._tls.handshake(null); // No handshake in server mode + stream = new WSC.IOStreamTls(acceptInfo.clientSocketId); + } else + stream = new WSC.IOStream(acceptInfo.clientSocketId) this.adopt_stream(acceptInfo, stream) } }, @@ -569,7 +575,8 @@ handler.finish() } } - } + }; + function BaseHandler() { this.headersWritten = false From 5a57d6125656e112b2961161b923712190026b47 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Fri, 2 Apr 2021 21:03:44 +0200 Subject: [PATCH 06/11] Add .gitignore --- .gitignore | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..69109601 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +**/node_modules +**/package-lock.json +react-ui/nojsx +wsc-chrome.min.js +assets +package.json +package.zip From f857b2057a6a08372e4b44935ec0ebfbb129f7c1 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Fri, 2 Apr 2021 21:11:37 +0200 Subject: [PATCH 07/11] More changes, got https to work --- makedeps/package.json | 3 +- manifest.json | 4 +- socket.js | 262 ++++-------------------------------------- stream.js | 64 +++++------ webapp.js | 3 +- 5 files changed, 59 insertions(+), 277 deletions(-) diff --git a/makedeps/package.json b/makedeps/package.json index b7353114..b68c7cb6 100644 --- a/makedeps/package.json +++ b/makedeps/package.json @@ -12,9 +12,10 @@ "@material-ui/icons": "^4.5.1", "babel": "^6.23.0", "browserify": "^16.5.0", - "node-forge": "^0.8.0", + "node-forge": "^0.10.0", "react": "^16.12.0", "react-dom": "^16.12.0", + "requirejs": "^2.3.6", "underscore": "^1.9.1" } } diff --git a/manifest.json b/manifest.json index ebe55e16..8cc85d85 100644 --- a/manifest.json +++ b/manifest.json @@ -10,7 +10,9 @@ "minimum_chrome_version": "45", "app": { "background": { - "scripts": ["underscore.js","encoding.js","common.js", "assets/bundle.js", "log-full.js","mime.js","buffer.js","request.js","socket.js","stream.js","chromesocketxhr.js","connection.js","webapp.js","websocket.js","handlers.js","httplib.js","upnp.js","background.js"] + "scripts": ["underscore.js","encoding.js","common.js","assets/bundle.js", + "log-full.js", "mime.js", "buffer.js","request.js","socket.js","stream.js", "chromesocketxhr.js", + "connection.js","webapp.js","websocket.js","handlers.js","httplib.js","upnp.js","background.js"] } }, "permissions": [ diff --git a/socket.js b/socket.js index 8aa7d148..881a0247 100644 --- a/socket.js +++ b/socket.js @@ -1,6 +1,5 @@ (function() { - // function to create certificate var createCert = function(cn, data) { console.log( @@ -22,13 +21,13 @@ var createCert = function(cn, data) { value: 'SE' }, { shortName: 'ST', - value: 'Kronoberg' + value: 'test-st' }, { name: 'localityName', - value: 'Växjö' + value: 'test-locality' }, { name: 'organizationName', - value: 'Test' + value: 'Testapp' }, { shortName: 'OU', value: 'Test' @@ -57,7 +56,7 @@ var createCert = function(cn, data) { cert.publicKey = keys.publicKey; // self-sign certificate - cert.sign(keys.privateKey); + cert.sign(keys.privateKey, forge.md.sha256.create()); // save data data[cn] = { @@ -65,7 +64,7 @@ var createCert = function(cn, data) { privateKey: forge.pki.privateKeyToPem(keys.privateKey) }; - console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); + //console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); }; var end = {}; @@ -73,12 +72,13 @@ var data = {}; // create certificate for server and client createCert('server', data); -//createCert('client', data); +createCert('client', data); console.log(data.server.privateKey); console.log(data.server.cert); -/* + var success = false; +let secret = "My secret message", response, roundtrip; // create TLS client end.client = forge.tls.createConnection({ @@ -99,12 +99,12 @@ end.client = forge.tls.createConnection({ }, connected: function(c) { console.log('Client connected...'); - +/* // send message to server setTimeout(function() { c.prepareHeartbeatRequest('heartbeat'); c.prepare('Hello Server'); - }, 1); + }, 1);*/ }, getCertificate: function(c, hint) { console.log('Client getting certificate ...'); @@ -118,9 +118,9 @@ end.client = forge.tls.createConnection({ end.server.process(c.tlsData.getBytes()); }, dataReady: function(c) { - var response = c.data.getBytes(); - console.log('Client received \"' + response + '\"'); - success = (response === 'Hello Client'); + roundtrip = c.data.getBytes(); + console.log('Client received \"' + roundtrip + '\"'); + success = (roundtrip === secret); c.close(); }, heartbeatReceived: function(c, payload) { @@ -172,10 +172,11 @@ end.server = forge.tls.createConnection({ end.client.process(c.tlsData.getBytes()); }, dataReady: function(c) { - console.log('Server received \"' + c.data.getBytes() + '\"'); + response = c.data.getBytes(); + console.log('Server received \"' + response + '\"'); // send response - c.prepare('Hello Client'); + c.prepare(response); c.close(); }, heartbeatReceived: function(c, payload) { @@ -189,238 +190,15 @@ end.server = forge.tls.createConnection({ } }); -//console.log('created TLS client and server, doing handshake...'); -//end.client.handshake(); +console.log('created TLS client and server, doing handshake...'); +end.client.handshake(); +end.client.prepare(secret); +console.log("sucess:" + success); //WSC.Tls = {end: end, data: data }; -*/ - - - - - // the Ssl sockets - var string2ArrayBuffer = function(string, callback) { - var buf = new ArrayBuffer(string.length); - var bufView = new Uint8Array(buf); - for (var i=0; i < string.length; i++) { - bufView[i] = string.charCodeAt(i); - } - callback(buf); - }; - var arrayBuffer2String = function(buf, callback) { - var bufView = new Uint8Array(buf); - var chunkSize = 65536; - var result = ''; - for (var i = 0; i < bufView.length; i += chunkSize) { - result += String.fromCharCode.apply(null, bufView.subarray(i, Math.min(i + chunkSize, bufView.length))); - } - callback(result); - }; - - var SocketSslTcp = function() { - this._buffer = ''; - this._requiredBytes = 0; - this._onReceive = this._onReceive.bind(this); - this._onReceiveError = this._onReceiveError.bind(this); - //chrome.sockets.tcp.apply(this); //net.AbstractTCPSocket.apply(this); - }; - - //SocketSslTcp.prototype.__proto__ = net.AbstractTCPSocket.prototype; - SocketSslTcp.prototype = Object.create(chrome.sockets.tcp, {constructor: {value: SocketSslTcp}}) - -/* // implementation in webapp.js - SocketSslTcp.prototype.connect = function(addr, port) { - var _this = this; - this._active(); - chrome.sockets.tcp.create({}, function(si) { - _this.socketId = si.socketId; - if (_this.socketId > 0) { - registerSocketConnection(si.socketId); - chrome.sockets.tcp.setPaused(_this.socketId, true); - // Port will be of the form +port# given that it is using SSL. - chrome.sockets.tcp.connect(_this.socketId, addr, parseInt(port.substr(1)), - _this._onConnect.bind(_this)); - } else { - _this.emit('error', "Couldn\'t create socket"); - } - }); - };*/ - - SocketSslTcp.prototype._onConnect = function(rc) { - if (rc < 0) { - this.emit('error', 'Couldn\'t connect to socket: ' + - chrome.runtime.lastError.message + ' (error ' + (-rc) + ')'); - return; - } - this._initializeTls({}); - this._tls.handshake(this._tlsOptions.sessionId || null); - chrome.sockets.tcp.onReceive.addListener(this._onReceive); - chrome.sockets.tcp.onReceiveError.addListener(this._onReceiveError); - chrome.sockets.tcp.setPaused(this.socketId, false); - }; - - SocketSslTcp.prototype._initializeTls = function(options) { - var _this = this; - this._tlsOptions = options; - this._tls = window.forge.tls.createConnection({ - server: false, - sessionId: options.sessionId || null, - caStore: options.caStore || [], - sessionCache: options.sessionCache || null, - cipherSuites: options.cipherSuites || [ - window.forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, - window.forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], - virtualHost: options.virtualHost, - verify: options.verify || function() { return true }, - getCertificate: options.getCertificate, - getPrivateKey: options.getPrivateKey, - getSignature: options.getSignature, - deflate: options.deflate, - inflate: options.inflate, - connected: function(c) { - // first handshake complete, call handler -// if(c.handshakes === 1) { - console.log('TLS socket connected'); - _this.emit('connect'); -// } - }, - tlsDataReady: function(c) { - // send TLS data over socket - var bytes = c.tlsData.getBytes(); - string2ArrayBuffer(bytes, function(data) { - chrome.sockets.tcp.send(_this.socketId, data, function(sendInfo) { - if (sendInfo.resultCode < 0) { - console.error('SOCKET ERROR on write: ' + - chrome.runtime.lastError.message + ' (error ' + (-sendInfo.resultCode) + ')'); - } - if (sendInfo.bytesSent === data.byteLength) { - _this.emit('drain'); - } else { - if (sendInfo.bytesSent >= 0) { - console.error('Can\'t handle non-complete writes: wrote ' + - sendInfo.bytesSent + ' expected ' + data.byteLength); - } - _this.emit('error', 'Invalid write on socket, code: ' + sendInfo.resultCode); - } - }); - }); - }, - dataReady: function(c) { - // indicate application data is ready - var data = c.data.getBytes(); - irc.util.toSocketData(forge.util.decodeUtf8(data), function(data) { - _this.emit('data', data); - }); - }, - closed: function(c) { - // close socket - _this._close(); - }, - error: function(c, e) { - // send error, close socket - _this.emit('error', 'tlsError: ' + e.message); - _this._close(); - } - }); - }; - SocketSslTcp.prototype._onClosed = function() { - if (this._tls && this._tls.open && this._tls.handshaking) { - this.emit('error', 'Connection closed during handshake'); - } - }; - - SocketSslTcp.prototype.close = function() { - if (this._tls) - this._tls.close(); - }; - - SocketSslTcp.prototype._close = function() { - if (this.socketId != null) { - chrome.sockets.tcp.onReceive.removeListener(this._onReceive); - chrome.sockets.tcp.onReceiveError.removeListener(this._onReceiveError); - chrome.sockets.tcp.disconnect(this.socketId); - chrome.sockets.tcp.close(this.socketId); - registerSocketConnection(this.socketId, true); - } - this.emit('close'); - }; - - SocketSslTcp.prototype.write = function(data) { - var _this = this; - arrayBuffer2String(data, function(data) { - _this._tls.prepare(data); - }); - }; - - SocketSslTcp.prototype._onReceive = function(receiveInfo) { - if (receiveInfo.socketId != this.socketId) - return; - this._active(); - if (!this._tls.open) - return; - var _this = this; - arrayBuffer2String(receiveInfo.data, function (data) { - _this._buffer += data; - if (_this._buffer.length >= _this._requiredBytes) { - _this._requiredBytes = _this._tls.process(_this._buffer); - _this._buffer = ''; - } - }); - }; - - SocketSslTcp.prototype._onReceiveError = function (readInfo) { - if (readInfo.socketId != this.socketId) - return; - this._active(); - if (info.resultCode === -100) { // connection closed - this.emit('end'); - this._close(); - } - else { - var message = ''; - if (chrome.runtime.lastError) - message = chrome.runtime.lastError.message; - this.emit('error', 'read from socket: ' + message + ' (error ' + - (-readInfo.resultCode) + ')'); - this._close(); - return; - } - }; - - - // wrapper for socket.tcp - var SocketTcp = function() { } - SocketTcp.prototype = Object.create(chrome.sockets.tcp, {constructor: {value: SocketTcp}}); - SocketTcp.prototype.onReceive = { - addListener:function(cb) { - chrome.sockets.tcp.onReceive.addListener(function(){ - console.log("SocketTcp.onReceive", arguments); - cb.apply(this, arguments); - }); - } - } - - - - var SocketsSingleton = function() { } - SocketsSingleton.prototype = Object.create(chrome.sockets, {constructor: {value: SocketsSingleton}}); - SocketsSingleton.prototype.setSsl = function(useSsl) { - if (!useSsl) { - SocketsSingleton.prototype.tcp = new SocketTcp; //chrome.sockets.tcp; - SocketsSingleton.prototype.udp = chrome.sockets.udp; - SocketsSingleton.prototype.tcpServer = chrome.sockets.tcpServer; - } else { - console.warn("Not ready yet"); - SocketsSingleton.prototype.tcp = new SocketSslTcp; //chrome.sockets.tcp; - SocketsSingleton.prototype.udp = chrome.sockets.udp; - SocketsSingleton.prototype.tcpServer = chrome.sockets.tcpServer; - } - } - WSC.Sockets = new SocketsSingleton; - WSC.Sockets.setSsl(true); })(); diff --git a/stream.js b/stream.js index 83a0b79d..8f7c62cc 100644 --- a/stream.js +++ b/stream.js @@ -1,39 +1,39 @@ (function() { const serverCert = -'-----BEGIN CERTIFICATE-----\ -MIICcDCCAdmgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQ8wDQYDVQQDEwZzZXJ2\ -ZXIxCzAJBgNVBAYTAlNFMRIwEAYDVQQIEwlLcm9ub2JlcmcxDjAMBgNVBAcTBVbk\ -eGr2MQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MB4XDTIxMDQwMTExMzU0\ -NloXDTIyMDQwMTExMzU0NlowYDEPMA0GA1UEAxMGc2VydmVyMQswCQYDVQQGEwJT\ -RTESMBAGA1UECBMJS3Jvbm9iZXJnMQ4wDAYDVQQHEwVW5Hhq9jENMAsGA1UEChME\ -VGVzdDENMAsGA1UECxMEVGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA\ -kojUsq1rKK2lm5XjRKHBPcbWPZxIIvWqwTTYEyi8ds8fYpovqiYFg9Jhp+maK8wx\ -t/xXEx10hkZIG6Bhbj80DXWm+CeNxxuZJnQw4eg68DCpFgRNFXtz+U3GtCgZYjQ4\ -E8iUMcRqIJK7OGJslfhVCEfsBs64/bO9V45jBMWyQDMCAwEAAaM6MDgwDAYDVR0T\ -BAUwAwEB/zALBgNVHQ8EBAMCAvQwGwYDVR0RBBQwEoYQaHR0cDovL2xvY2FsaG9z\ -dDANBgkqhkiG9w0BAQUFAAOBgQBnO8VP6AKmWi0MmVOBWvg45dfUN6OVWGZATJ5k\ -1t0P/OboXCBxBu/H2PxIA7k43eSJOwJOTsmfEiRk27Kys2FXy1uhIUKCyIHs49xE\ -Xa+HWyUgHX+/V0sKdPbnQu5dF9+vlpX087114qRv6ynrBbVh8e9eYuLSoXnRHvmk\ -WvUyJA==\ ------END CERTIFICATE-----'; +"-----BEGIN CERTIFICATE-----\n\ +MIICgjCCAeugAwIBAgIBATANBgkqhkiG9w0BAQsFADBpMQ8wDQYDVQQDEwZzZXJ2\n\ +ZXIxCzAJBgNVBAYTAlNFMRAwDgYDVQQIEwd0ZXN0LXN0MRYwFAYDVQQHEw10ZXN0\n\ +LWxvY2FsaXR5MRAwDgYDVQQKEwdUZXN0YXBwMQ0wCwYDVQQLEwRUZXN0MB4XDTIx\n\ +MDQwMjE4NDMwOVoXDTIyMDQwMjE4NDMwOVowaTEPMA0GA1UEAxMGc2VydmVyMQsw\n\ +CQYDVQQGEwJTRTEQMA4GA1UECBMHdGVzdC1zdDEWMBQGA1UEBxMNdGVzdC1sb2Nh\n\ +bGl0eTEQMA4GA1UEChMHVGVzdGFwcDENMAsGA1UECxMEVGVzdDCBnzANBgkqhkiG\n\ +9w0BAQEFAAOBjQAwgYkCgYEAltdStr9uz5ndmHEoYa7fuByeH5xf3r8qxYM2i0mL\n\ +LL4zENjjtyjoucHs+s6M3UpXEJYeo8wp5pYgAvAJsiDox1TvlD7NsZW14yZE5Z59\n\ +P40E1UfMVvdB1s/yVIvwzsjp61T7qg0ZvRlCVDW5ibHKMhEFAaSkxv4l85TBkePL\n\ +MDMCAwEAAaM6MDgwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAvQwGwYDVR0RBBQw\n\ +EoYQaHR0cDovL2xvY2FsaG9zdDANBgkqhkiG9w0BAQsFAAOBgQBRMcCIXhW4I0uA\n\ +dpWlgUpQzDz2aesgP7GdtOOh/b/kP2dxjzIC1Maobhiylzi/EFnHAQumNpTmlCFr\n\ +EEhGjcQ8/FEuhhMIizCKIuj5hXKgHy/cT9GYhVZ2jWk7nC4Bv4kghWDzcymW1TtI\n\ +qPB0mRGeBl+rnnQYRMd2AyOcspI5RQ==\n\ +-----END CERTIFICATE-----"; const privateKey = -'-----BEGIN RSA PRIVATE KEY-----\ -MIICXgIBAAKBgQCSiNSyrWsoraWbleNEocE9xtY9nEgi9arBNNgTKLx2zx9imi+q\ -JgWD0mGn6ZorzDG3/FcTHXSGRkgboGFuPzQNdab4J43HG5kmdDDh6DrwMKkWBE0V\ -e3P5Tca0KBliNDgTyJQxxGogkrs4YmyV+FUIR+wGzrj9s71XjmMExbJAMwIDAQAB\ -AoGAFEp0QYW4B/r7qq63uMI5UweclQ12A7lG+tgJb6W9aypFK080eHgpXVadhTXY\ -zmXJILQFjrUOdKV4yLKNq0l/OIQrUXOjs0ulIyN71WBReZmeT/5uTi9/b9IOThiw\ -2Nl8mc8zHxChkNtb231Js9NA2XW9/ivOu1nXph6qvxvzB/kCQQDN/blSMWaYFIfW\ -cGs+Z/W3ZOps5A7y1EhAqd3X6RgGIvsaRTyhi6TUr8zx+L0v/yKpReI1xVErkH+H\ -BZ12bDHfAkEAthvmJPagriiM4hqYrfmgpwY7wz06KZGiZYujpjqSKTCB74fKvphe\ -jDwkPBctBFiVvgiC72qSbAzpdAf2tNoELQJBALBlOqJY7WsEAcKvKBcbvT3b7Cdt\ -MCPfhzPggrmWwNzYbcD0U1RfGbqMBOucvp1wVQUxc+Hp43Vz2tEMDOhRBG8CQQCS\ -KGwbKJInlUYVRlFZ+Gq3Auq+NQrUSB11sJBEnuemBVeT3oGbXQEtPiu6ysMHpO1x\ -2rTz4K3p6KcJyEZ6Oix1AkEAjAOWXdP3Kv0hFPB6PVKTZRKeQYDzT6gzEmXMmwpT\ -bKvn7lSUQKst5Br8W/BiEs15HtRZIxIzlIqWzAodxMZghw==\ ------END RSA PRIVATE KEY-----'; +"-----BEGIN RSA PRIVATE KEY-----\n\ +MIICWwIBAAKBgQCW11K2v27Pmd2YcShhrt+4HJ4fnF/evyrFgzaLSYssvjMQ2OO3\n\ +KOi5wez6zozdSlcQlh6jzCnmliAC8AmyIOjHVO+UPs2xlbXjJkTlnn0/jQTVR8xW\n\ +90HWz/JUi/DOyOnrVPuqDRm9GUJUNbmJscoyEQUBpKTG/iXzlMGR48swMwIDAQAB\n\ +AoGAYiEka0Twhtf3ZDPBbIMCgdkEOVZWvCcrYSDye/zVML9vozcmNULE3Au/6o4y\n\ +78dsCptOxYqNe7gQjTixZhOouvzaVFAIZ8cbxfwYIBUFqNncTePSOOZOGVe5ufvT\n\ +Pa8rb4SgDl2aRCyo4wrPE9laXpcJsenA/ZdloezKcZHZsMECQQDIK6LMt2bNXPPS\n\ +iYrLJOg5fxos0gRvHMx/lmhRunHSOO5v7GdPCG9NTMfu/IwX+7aY9h4xbYisUhdg\n\ +2xMgVtghAkEAwOmGJ+XQMtO+U1QyeYgvdaUQSjPDQBRHKHogfizqQg7+2hLyj50C\n\ +y6WFuKXn0e9WypNgicf3fqfPPhmH6BFt0wJAOslN649lOqS02r0YLObu6IvidQ1M\n\ +zhEIIeRbSL1X1iRwKiCkinpwraQCB7bVselzy+JkJaIEhI8rXH+aU2IN4QI/BgdG\n\ +KfkEiJIVYIVBDosy8Ho4CBmWAGqhzqICYe8FYwsU67ur2NEPRU3m395PYEAadjok\n\ +yil1kn+r+kTR+m6RAkEAkIOQOleOZ+btbQTETMEDFnO/g6cuVhSXoemGmY6BY8k4\n\ +14AmYpksffL217BZU5OUcWVfCyNBfYZCklaakhK9Jw==\n\ +-----END RSA PRIVATE KEY-----"; var peerSockMap = {} WSC.peerSockMap = peerSockMap @@ -298,7 +298,7 @@ bKvn7lSUQKst5Br8W/BiEs15HtRZIxIzlIqWzAodxMZghw==\ console.log('Server connected'); //c.prepareHeartbeatRequest('heartbeat'); }, - verifyClient: false, + verifyClient: false,// true, // verify: function(c, verified, depth, certs) { // console.log( // 'Server verifying certificate w/CN: \"' + diff --git a/webapp.js b/webapp.js index 86d6b962..49763fcc 100644 --- a/webapp.js +++ b/webapp.js @@ -326,7 +326,8 @@ //console.log('onListen',result) this.starting = false this.started = true - console.log('Listening on','http://'+ this.get_host() + ':' + this.port+'/') + let prot = this.opts.optUseTls ? 'http' : 'https'; + console.log('Listening on',prot+'://'+ this.get_host() + ':' + this.port+'/') this.bindAcceptCallbacks() this.init_urls() this.start_success({urls:this.urls}) // initialize URLs ? From 6f98b4793c7b0d40816c93f6d45c15aae1d137f8 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Sat, 3 Apr 2021 19:04:44 +0200 Subject: [PATCH 08/11] Added https functionality to GUI --- socket.js => crypto.js | 17 ++++++----- makedeps/index.js | 3 ++ makedeps/package.json | 1 + manifest.json | 2 +- minimize.sh | 2 +- react-ui/js/index.js | 65 +++++++++++++++++++++++++++++++++++++----- react-ui/js/options.js | 17 +++++++++++ stream.js | 45 +++++++++-------------------- webapp.js | 16 ++++++----- 9 files changed, 114 insertions(+), 54 deletions(-) rename socket.js => crypto.js (94%) diff --git a/socket.js b/crypto.js similarity index 94% rename from socket.js rename to crypto.js index 881a0247..601932d1 100644 --- a/socket.js +++ b/crypto.js @@ -1,7 +1,7 @@ (function() { // function to create certificate -var createCert = function(cn, data) { +var createCrypto = function(cn, data) { console.log( 'Generating 1024-bit key-pair and certificate for \"' + cn + '\".'); var keys = forge.pki.rsa.generateKeyPair(1024); @@ -12,7 +12,7 @@ var createCert = function(cn, data) { cert.validity.notBefore = new Date(); cert.validity.notAfter = new Date(); cert.validity.notAfter.setFullYear( - cert.validity.notBefore.getFullYear() + 1); + cert.validity.notBefore.getFullYear() + 10); var attrs = [{ name: 'commonName', value: cn @@ -24,13 +24,13 @@ var createCert = function(cn, data) { value: 'test-st' }, { name: 'localityName', - value: 'test-locality' + value: 'testing server' }, { name: 'organizationName', - value: 'Testapp' + value: 'Web server for chrome' }, { shortName: 'OU', - value: 'Test' + value: 'WSC' }]; cert.setSubject(attrs); cert.setIssuer(attrs); @@ -64,6 +64,7 @@ var createCert = function(cn, data) { privateKey: forge.pki.privateKeyToPem(keys.privateKey) }; + return data; //console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); }; @@ -71,11 +72,13 @@ var end = {}; var data = {}; // create certificate for server and client -createCert('server', data); -createCert('client', data); +createCrypto('server', data); +createCrypto('client', data); console.log(data.server.privateKey); console.log(data.server.cert); +WSC.createCrypto = (name) => { return createCrypto(name, {}); } + var success = false; let secret = "My secret message", response, roundtrip; diff --git a/makedeps/index.js b/makedeps/index.js index 9e9bdf61..b922d82e 100644 --- a/makedeps/index.js +++ b/makedeps/index.js @@ -9,6 +9,9 @@ window.ReactDOM = m m = require('@material-ui/core') window.MaterialUI = m +m = require('@material-ui/lab'); +window.MaterialUILab = m + m = require('underscore') window._ = m diff --git a/makedeps/package.json b/makedeps/package.json index b68c7cb6..45d3af5f 100644 --- a/makedeps/package.json +++ b/makedeps/package.json @@ -10,6 +10,7 @@ "@babel/plugin-transform-react-jsx": "^7.13.12", "@material-ui/core": "^4.6.1", "@material-ui/icons": "^4.5.1", + "@material-ui/lab": "^4.0.0-alpha.57", "babel": "^6.23.0", "browserify": "^16.5.0", "node-forge": "^0.10.0", diff --git a/manifest.json b/manifest.json index 8cc85d85..81854e39 100644 --- a/manifest.json +++ b/manifest.json @@ -11,7 +11,7 @@ "app": { "background": { "scripts": ["underscore.js","encoding.js","common.js","assets/bundle.js", - "log-full.js", "mime.js", "buffer.js","request.js","socket.js","stream.js", "chromesocketxhr.js", + "log-full.js", "mime.js", "buffer.js","request.js","crypto.js","stream.js", "chromesocketxhr.js", "connection.js","webapp.js","websocket.js","handlers.js","httplib.js","upnp.js","background.js"] } }, diff --git a/minimize.sh b/minimize.sh index 902be54b..2862f793 100644 --- a/minimize.sh +++ b/minimize.sh @@ -1 +1 @@ -cat "underscore.js" "encoding.js" "common.js" "log-full.js" "mime.js" "buffer.js" "request.js" "socket.js" "stream.js" "chromesocketxhr.js" "connection.js" "webapp.js" "websocket.js" "upnp.js" "handlers.js" "httplib.js" > wsc-chrome.min.js +cat "underscore.js" "encoding.js" "common.js" "log-full.js" "mime.js" "buffer.js" "request.js" "crypto.js" "stream.js" "chromesocketxhr.js" "connection.js" "webapp.js" "websocket.js" "upnp.js" "handlers.js" "httplib.js" > wsc-chrome.min.js diff --git a/react-ui/js/index.js b/react-ui/js/index.js index 7dc31237..3fbe97c2 100644 --- a/react-ui/js/index.js +++ b/react-ui/js/index.js @@ -12,9 +12,11 @@ const { Toolbar, Typography, Button, - ThemeProvider, + ThemeProvider } = MaterialUI +const {Alert} = MaterialUILab; + const {createMuiTheme, colors, withStyles} = MaterialUI; const styles = { card: {margin: '10px'}, @@ -84,7 +86,25 @@ const functions = { webapp.opts.optBackground = val bg.backgroundSettingChange({'optBackground':val}) } - } + }, + optPrivateKey: (app, k, val) => { + console.log('privateKey') + console.assert(typeof val === 'string') + app.webapp.updateOption('optPrivateKey', val); + }, + optCertificate: (app, k, val) => { + console.log('certificate', val); + console.assert(typeof val === 'string') + app.webapp.updateOption('optCertificate', val); + }, + optUseHttps: (app, k, val) => { + console.log("useHttps", val); + app.webapp.updateOption('optUseHttps', val); + if (app.webapp.started) { + app.webapp.stop(); + app.webapp.start(); + } + } }; @@ -118,7 +138,7 @@ class App extends React.Component { starting: false, lasterr: null, folder: null, - message: '', + message: '' } constructor(props) { super(props) @@ -174,6 +194,21 @@ class App extends React.Component { interfaces: this.webapp.urls.slice() }) } + gen_crypto() { + let reasonStr = this.webapp.opts.optPrivateKey ? "private key" : + this.webapp.opts.optCertificate ? "certificate" : ""; + if (reasonStr) { + console.warn("Would overwrite existing " + reasonStr + ", erase it first\nMake sure to save a copy first"); + return; + } + let cn = "WebServerForChrome" + (new Date()).toISOString(); + let data = this.webapp.createCrypto(cn); + this.setState({optPrivateKey: data[cn].privateKey, optCertificate: data[cn].cert}); + this.appOptions.set('optPrivateKey', data[cn].privateKey); + this.appOptions.set('optCertificate', data[cn].cert); + this.webapp.updateOption('optPrivateKey', data[cn].privateKey); + this.webapp.updateOption('optCertificate', data[cn].cert); + } ui_ready() { if (this.webapp) { if (! (this.webapp.started || this.webapp.starting)) { @@ -225,9 +260,12 @@ class App extends React.Component { optModRewriteEnable: null, optModRewriteRegexp: ['optModRewriteEnable'], optModRewriteNegate: ['optModRewriteEnable'], - optModRewriteTo: ['optModRewriteEnable'] - } - console.assert(this) + optModRewriteTo: ['optModRewriteEnable'], + optUseHttps: null, + optPrivateKey: null, + optCertificate: null + }; + console.assert(this); const renderOpts = (opts) => { const _this = this; @@ -253,6 +291,19 @@ class App extends React.Component { this.setState({showAdvanced: !this.state.showAdvanced}) }} >{this.state.showAdvanced ? 'Hide Advanced Options' : 'Show Advanced Options'}) + + const genCryptoButton = (
+ {this.webapp && (this.webapp.opts.optPrivateKey || this.webapp.opts.optCertificate) && + To regenerate, remove key and cert. Be sure to take a copy first, for possible later use!} + +
) + const {state} = this; return (
@@ -316,7 +367,7 @@ class App extends React.Component { {options} {advancedButton} - {state.showAdvanced &&
{advOptions}
} + {state.showAdvanced &&
{advOptions}{genCryptoButton}
} diff --git a/react-ui/js/options.js b/react-ui/js/options.js index d6f2af11..98b26163 100644 --- a/react-ui/js/options.js +++ b/react-ui/js/options.js @@ -69,6 +69,7 @@ export function AppOption({disabled, indent, name, value, appOptions, onChange: Date: Sat, 3 Apr 2021 19:10:52 +0200 Subject: [PATCH 09/11] Cleanup --- crypto.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crypto.js b/crypto.js index 601932d1..5e0f4b2c 100644 --- a/crypto.js +++ b/crypto.js @@ -68,6 +68,12 @@ var createCrypto = function(cn, data) { //console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); }; + +WSC.createCrypto = (name) => { return createCrypto(name, {}); } + + +/* +// testing tls var end = {}; var data = {}; @@ -76,10 +82,6 @@ createCrypto('server', data); createCrypto('client', data); console.log(data.server.privateKey); console.log(data.server.cert); - -WSC.createCrypto = (name) => { return createCrypto(name, {}); } - - var success = false; let secret = "My secret message", response, roundtrip; @@ -107,7 +109,7 @@ end.client = forge.tls.createConnection({ setTimeout(function() { c.prepareHeartbeatRequest('heartbeat'); c.prepare('Hello Server'); - }, 1);*/ + }, 1);*//* }, getCertificate: function(c, hint) { console.log('Client getting certificate ...'); @@ -200,7 +202,7 @@ console.log("sucess:" + success); //WSC.Tls = {end: end, data: data }; - +*/ From a778e676f42f2017ddd6ef676ee62c46468fbeab Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Sat, 3 Apr 2021 20:30:53 +0200 Subject: [PATCH 10/11] More cleanup before pull request --- background.js | 6 ++- crypto.js | 140 +------------------------------------------------- stream.js | 36 ------------- 3 files changed, 7 insertions(+), 175 deletions(-) diff --git a/background.js b/background.js index a464d6d5..30b1bf3f 100644 --- a/background.js +++ b/background.js @@ -33,7 +33,11 @@ function onchoosefolder(entry) { function settings_ready(d) { localOptions = d - console.log('settings:',d) + let dCpy = {}; + Object.assign(dCpy, d); + delete dCpy.optPrivateKey;// dont fill logs with crypto info + delete dCpy.optCertificate; + console.log('settings:',dCpy) setTimeout( maybeStartup, 2000 ) // give background accept handler some time to trigger //chrome.alarms.getAll( onAllAlarms ) } diff --git a/crypto.js b/crypto.js index 5e0f4b2c..d5bdbe58 100644 --- a/crypto.js +++ b/crypto.js @@ -65,146 +65,10 @@ var createCrypto = function(cn, data) { }; return data; - //console.log('certificate created for \"' + cn + '\": \n' + data[cn].cert); + console.log('certificate created for \"' + cn + '\": \n'); }; - -WSC.createCrypto = (name) => { return createCrypto(name, {}); } - - -/* -// testing tls -var end = {}; -var data = {}; - -// create certificate for server and client -createCrypto('server', data); -createCrypto('client', data); -console.log(data.server.privateKey); -console.log(data.server.cert); -var success = false; -let secret = "My secret message", response, roundtrip; - -// create TLS client -end.client = forge.tls.createConnection({ - server: false, - caStore: [data.server.cert], - sessionCache: {}, - // supported cipher suites in order of preference - cipherSuites: [ - forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, - forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], - virtualHost: 'server', - verify: function(c, verified, depth, certs) { - console.log( - 'TLS Client verifying certificate w/CN: \"' + - certs[0].subject.getField('CN').value + - '\", verified: ' + verified + '...'); - return verified; - }, - connected: function(c) { - console.log('Client connected...'); -/* - // send message to server - setTimeout(function() { - c.prepareHeartbeatRequest('heartbeat'); - c.prepare('Hello Server'); - }, 1);*//* - }, - getCertificate: function(c, hint) { - console.log('Client getting certificate ...'); - return data.client.cert; - }, - getPrivateKey: function(c, cert) { - return data.client.privateKey; - }, - tlsDataReady: function(c) { - // send TLS data to server - end.server.process(c.tlsData.getBytes()); - }, - dataReady: function(c) { - roundtrip = c.data.getBytes(); - console.log('Client received \"' + roundtrip + '\"'); - success = (roundtrip === secret); - c.close(); - }, - heartbeatReceived: function(c, payload) { - console.log('Client received heartbeat: ' + payload.getBytes()); - }, - closed: function(c) { - console.log('Client disconnected.'); - if(success) { - console.log('PASS'); - } else { - console.log('FAIL'); - } - }, - error: function(c, error) { - console.log('Client error: ' + error.message); - } -}); - -// create TLS server -end.server = forge.tls.createConnection({ - server: true, - caStore: [data.client.cert], - sessionCache: {}, - // supported cipher suites in order of preference - cipherSuites: [ - forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, - forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], - connected: function(c) { - console.log('Server connected'); - c.prepareHeartbeatRequest('heartbeat'); - }, - verifyClient: true, - verify: function(c, verified, depth, certs) { - console.log( - 'Server verifying certificate w/CN: \"' + - certs[0].subject.getField('CN').value + - '\", verified: ' + verified + '...'); - return verified; - }, - getCertificate: function(c, hint) { - console.log('Server getting certificate for \"' + hint[0] + '\"...'); - return data.server.cert; - }, - getPrivateKey: function(c, cert) { - return data.server.privateKey; - }, - tlsDataReady: function(c) { - // send TLS data to client - end.client.process(c.tlsData.getBytes()); - }, - dataReady: function(c) { - response = c.data.getBytes(); - console.log('Server received \"' + response + '\"'); - - // send response - c.prepare(response); - c.close(); - }, - heartbeatReceived: function(c, payload) { - console.log('Server received heartbeat: ' + payload.getBytes()); - }, - closed: function(c) { - console.log('Server disconnected.'); - }, - error: function(c, error) { - console.log('Server error: ' + error.message); - } -}); - -console.log('created TLS client and server, doing handshake...'); -end.client.handshake(); -end.client.prepare(secret); -console.log("sucess:" + success); - -//WSC.Tls = {end: end, data: data }; - -*/ - - +WSC.createCrypto = (name) => { return createCrypto(name, {}); } })(); diff --git a/stream.js b/stream.js index 0b644ecb..e9d08cb1 100644 --- a/stream.js +++ b/stream.js @@ -1,41 +1,5 @@ (function() { -/* - const serverCert = -"-----BEGIN CERTIFICATE-----\n\ -MIICgjCCAeugAwIBAgIBATANBgkqhkiG9w0BAQsFADBpMQ8wDQYDVQQDEwZzZXJ2\n\ -ZXIxCzAJBgNVBAYTAlNFMRAwDgYDVQQIEwd0ZXN0LXN0MRYwFAYDVQQHEw10ZXN0\n\ -LWxvY2FsaXR5MRAwDgYDVQQKEwdUZXN0YXBwMQ0wCwYDVQQLEwRUZXN0MB4XDTIx\n\ -MDQwMjE4NDMwOVoXDTIyMDQwMjE4NDMwOVowaTEPMA0GA1UEAxMGc2VydmVyMQsw\n\ -CQYDVQQGEwJTRTEQMA4GA1UECBMHdGVzdC1zdDEWMBQGA1UEBxMNdGVzdC1sb2Nh\n\ -bGl0eTEQMA4GA1UEChMHVGVzdGFwcDENMAsGA1UECxMEVGVzdDCBnzANBgkqhkiG\n\ -9w0BAQEFAAOBjQAwgYkCgYEAltdStr9uz5ndmHEoYa7fuByeH5xf3r8qxYM2i0mL\n\ -LL4zENjjtyjoucHs+s6M3UpXEJYeo8wp5pYgAvAJsiDox1TvlD7NsZW14yZE5Z59\n\ -P40E1UfMVvdB1s/yVIvwzsjp61T7qg0ZvRlCVDW5ibHKMhEFAaSkxv4l85TBkePL\n\ -MDMCAwEAAaM6MDgwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAvQwGwYDVR0RBBQw\n\ -EoYQaHR0cDovL2xvY2FsaG9zdDANBgkqhkiG9w0BAQsFAAOBgQBRMcCIXhW4I0uA\n\ -dpWlgUpQzDz2aesgP7GdtOOh/b/kP2dxjzIC1Maobhiylzi/EFnHAQumNpTmlCFr\n\ -EEhGjcQ8/FEuhhMIizCKIuj5hXKgHy/cT9GYhVZ2jWk7nC4Bv4kghWDzcymW1TtI\n\ -qPB0mRGeBl+rnnQYRMd2AyOcspI5RQ==\n\ ------END CERTIFICATE-----"; - - const privateKey = -"-----BEGIN RSA PRIVATE KEY-----\n\ -MIICWwIBAAKBgQCW11K2v27Pmd2YcShhrt+4HJ4fnF/evyrFgzaLSYssvjMQ2OO3\n\ -KOi5wez6zozdSlcQlh6jzCnmliAC8AmyIOjHVO+UPs2xlbXjJkTlnn0/jQTVR8xW\n\ -90HWz/JUi/DOyOnrVPuqDRm9GUJUNbmJscoyEQUBpKTG/iXzlMGR48swMwIDAQAB\n\ -AoGAYiEka0Twhtf3ZDPBbIMCgdkEOVZWvCcrYSDye/zVML9vozcmNULE3Au/6o4y\n\ -78dsCptOxYqNe7gQjTixZhOouvzaVFAIZ8cbxfwYIBUFqNncTePSOOZOGVe5ufvT\n\ -Pa8rb4SgDl2aRCyo4wrPE9laXpcJsenA/ZdloezKcZHZsMECQQDIK6LMt2bNXPPS\n\ -iYrLJOg5fxos0gRvHMx/lmhRunHSOO5v7GdPCG9NTMfu/IwX+7aY9h4xbYisUhdg\n\ -2xMgVtghAkEAwOmGJ+XQMtO+U1QyeYgvdaUQSjPDQBRHKHogfizqQg7+2hLyj50C\n\ -y6WFuKXn0e9WypNgicf3fqfPPhmH6BFt0wJAOslN649lOqS02r0YLObu6IvidQ1M\n\ -zhEIIeRbSL1X1iRwKiCkinpwraQCB7bVselzy+JkJaIEhI8rXH+aU2IN4QI/BgdG\n\ -KfkEiJIVYIVBDosy8Ho4CBmWAGqhzqICYe8FYwsU67ur2NEPRU3m395PYEAadjok\n\ -yil1kn+r+kTR+m6RAkEAkIOQOleOZ+btbQTETMEDFnO/g6cuVhSXoemGmY6BY8k4\n\ -14AmYpksffL217BZU5OUcWVfCyNBfYZCklaakhK9Jw==\n\ ------END RSA PRIVATE KEY-----"; -*/ var peerSockMap = {} WSC.peerSockMap = peerSockMap From 3e20c133009b1ba1cacf890c73d35588318d39e7 Mon Sep 17 00:00:00 2001 From: Fredrik Johansson Date: Sun, 4 Apr 2021 02:39:44 +0200 Subject: [PATCH 11/11] Do suggestions from maintainer during pull request. --- crypto.js | 2 +- makedeps/package.json | 3 --- react-ui/js/index.js | 41 +++++++++++++++++++++++++---------------- stream.js | 2 +- webapp.js | 3 +-- 5 files changed, 28 insertions(+), 23 deletions(-) diff --git a/crypto.js b/crypto.js index d5bdbe58..6070af18 100644 --- a/crypto.js +++ b/crypto.js @@ -68,7 +68,7 @@ var createCrypto = function(cn, data) { console.log('certificate created for \"' + cn + '\": \n'); }; -WSC.createCrypto = (name) => { return createCrypto(name, {}); } +WSC.createCrypto = (name, data) => { return createCrypto(name, data || {}); } })(); diff --git a/makedeps/package.json b/makedeps/package.json index 45d3af5f..d4efff4f 100644 --- a/makedeps/package.json +++ b/makedeps/package.json @@ -7,16 +7,13 @@ "make": "./node_modules/.bin/browserify index.js > ../assets/bundle.js" }, "dependencies": { - "@babel/plugin-transform-react-jsx": "^7.13.12", "@material-ui/core": "^4.6.1", "@material-ui/icons": "^4.5.1", "@material-ui/lab": "^4.0.0-alpha.57", - "babel": "^6.23.0", "browserify": "^16.5.0", "node-forge": "^0.10.0", "react": "^16.12.0", "react-dom": "^16.12.0", - "requirejs": "^2.3.6", "underscore": "^1.9.1" } } diff --git a/react-ui/js/index.js b/react-ui/js/index.js index 3fbe97c2..65776158 100644 --- a/react-ui/js/index.js +++ b/react-ui/js/index.js @@ -20,7 +20,7 @@ const {Alert} = MaterialUILab; const {createMuiTheme, colors, withStyles} = MaterialUI; const styles = { card: {margin: '10px'}, - appicon: {marginRight: '10px'}, + appicon: {marginRight: '10px'} }; const theme = createMuiTheme({ palette: { @@ -88,12 +88,12 @@ const functions = { } }, optPrivateKey: (app, k, val) => { - console.log('privateKey') + //console.log('privateKey') console.assert(typeof val === 'string') app.webapp.updateOption('optPrivateKey', val); }, optCertificate: (app, k, val) => { - console.log('certificate', val); + //console.log('certificate'); console.assert(typeof val === 'string') app.webapp.updateOption('optCertificate', val); }, @@ -153,7 +153,12 @@ class App extends React.Component { } settings_ready() { const allOpts = this.appOptions.getAll() - console.log('fetched local settings', this.appOptions, allOpts) + let dCpy = {}; + Object.assign(dCpy, allOpts); + delete dCpy.optPrivateKey;// dont fill logs with crypto info + delete dCpy.optCertificate; + + console.log('fetched local settings', this.appOptions, dCpy) this.webapp = this.bg.get_webapp(allOpts) // retainStr in here this.bg.WSC.VERBOSE = this.bg.WSC.DEBUG = this.appOptions.get('optVerbose') this.webapp.on_status_change = this.on_webapp_change.bind(this) @@ -203,11 +208,12 @@ class App extends React.Component { } let cn = "WebServerForChrome" + (new Date()).toISOString(); let data = this.webapp.createCrypto(cn); - this.setState({optPrivateKey: data[cn].privateKey, optCertificate: data[cn].cert}); this.appOptions.set('optPrivateKey', data[cn].privateKey); this.appOptions.set('optCertificate', data[cn].cert); this.webapp.updateOption('optPrivateKey', data[cn].privateKey); this.webapp.updateOption('optCertificate', data[cn].cert); + this.setState({optPrivateKey: data[cn].privateKey, optCertificate: data[cn].cert}); + setTimeout(this.render, 50); // prevent race condition when ReactElement get set before opts have value } ui_ready() { if (this.webapp) { @@ -261,7 +267,9 @@ class App extends React.Component { optModRewriteRegexp: ['optModRewriteEnable'], optModRewriteNegate: ['optModRewriteEnable'], optModRewriteTo: ['optModRewriteEnable'], - optUseHttps: null, + optUseHttps: null + }; + const optHttpsInfo = { optPrivateKey: null, optCertificate: null }; @@ -292,17 +300,18 @@ class App extends React.Component { }} >{this.state.showAdvanced ? 'Hide Advanced Options' : 'Show Advanced Options'}
) - const genCryptoButton = (
- {this.webapp && (this.webapp.opts.optPrivateKey || this.webapp.opts.optCertificate) && - To regenerate, remove key and cert. Be sure to take a copy first, for possible later use!} - -
) + }}>Generate crypto} + )]; + })(); const {state} = this; return (
@@ -367,7 +376,7 @@ class App extends React.Component { {options} {advancedButton} - {state.showAdvanced &&
{advOptions}{genCryptoButton}
} + {state.showAdvanced &&
{advOptions}{httpsOptions}
} diff --git a/stream.js b/stream.js index e9d08cb1..098b727d 100644 --- a/stream.js +++ b/stream.js @@ -281,7 +281,7 @@ chrome.sockets.tcp.send( _t.sockId, b, cb); else _t.error("tlsData on closed socket"); - }, + }, dataReady: function(c) { // decrypted data from client let str = c.data.getBytes(); diff --git a/webapp.js b/webapp.js index 39752e9d..584456b8 100644 --- a/webapp.js +++ b/webapp.js @@ -6,7 +6,6 @@ console.log('initialize webapp with opts',opts) } opts = opts || {} - //opts.optUseHttps = true; /// FIXME hack this into a gui selectable thing this.id = Math.random().toString() this.opts = opts this.handlers = opts.handlers || [] @@ -327,7 +326,7 @@ //console.log('onListen',result) this.starting = false this.started = true - let prot = this.opts.optUseHttps ? 'https' : 'http'; + let prot = this.opts.optUseHttps ? 'https' : 'http'; console.log('Listening on',prot+'://'+ this.get_host() + ':' + this.port+'/') this.bindAcceptCallbacks() this.init_urls()