aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--controllers/api/v1/pods.js4
-rw-r--r--helpers/peertubeCrypto.js152
-rw-r--r--helpers/requests.js111
-rw-r--r--helpers/utils.js199
-rw-r--r--lib/friends.js9
-rw-r--r--lib/poolRequests.js30
-rw-r--r--middlewares/secure.js25
-rw-r--r--server.js7
8 files changed, 303 insertions, 234 deletions
diff --git a/controllers/api/v1/pods.js b/controllers/api/v1/pods.js
index 3e457ec57..29517ba8e 100644
--- a/controllers/api/v1/pods.js
+++ b/controllers/api/v1/pods.js
@@ -8,11 +8,11 @@
8 var friends = require('../../../lib/friends') 8 var friends = require('../../../lib/friends')
9 var middleware = require('../../../middlewares') 9 var middleware = require('../../../middlewares')
10 var cacheMiddleware = middleware.cache 10 var cacheMiddleware = middleware.cache
11 var peertubeCrypto = require('../../../helpers/peertubeCrypto')
11 var Pods = require('../../../models/pods') 12 var Pods = require('../../../models/pods')
12 var reqValidator = middleware.reqValidators.pods 13 var reqValidator = middleware.reqValidators.pods
13 var secureMiddleware = middleware.secure 14 var secureMiddleware = middleware.secure
14 var secureRequest = middleware.reqValidators.remote.secureRequest 15 var secureRequest = middleware.reqValidators.remote.secureRequest
15 var utils = require('../../../helpers/utils')
16 var Videos = require('../../../models/videos') 16 var Videos = require('../../../models/videos')
17 17
18 var router = express.Router() 18 var router = express.Router()
@@ -37,7 +37,7 @@
37 37
38 Videos.addRemotes(informations.videos) 38 Videos.addRemotes(informations.videos)
39 39
40 fs.readFile(utils.getCertDir() + 'peertube.pub', 'utf8', function (err, cert) { 40 fs.readFile(peertubeCrypto.getCertDir() + 'peertube.pub', 'utf8', function (err, cert) {
41 if (err) { 41 if (err) {
42 logger.error('Cannot read cert file.', { error: err }) 42 logger.error('Cannot read cert file.', { error: err })
43 return next(err) 43 return next(err)
diff --git a/helpers/peertubeCrypto.js b/helpers/peertubeCrypto.js
new file mode 100644
index 000000000..3e757659b
--- /dev/null
+++ b/helpers/peertubeCrypto.js
@@ -0,0 +1,152 @@
1;(function () {
2 'use strict'
3
4 var config = require('config')
5 var crypto = require('crypto')
6 var fs = require('fs')
7 var openssl = require('openssl-wrapper')
8 var ursa = require('ursa')
9
10 var logger = require('./logger')
11
12 var certDir = __dirname + '/../' + config.get('storage.certs')
13 var algorithm = 'aes-256-ctr'
14
15 var peertubeCrypto = {
16 checkSignature: checkSignature,
17 createCertsIfNotExist: createCertsIfNotExist,
18 decrypt: decrypt,
19 encrypt: encrypt,
20 getCertDir: getCertDir,
21 sign: sign
22 }
23
24 function checkSignature (public_key, raw_data, hex_signature) {
25 var crt = ursa.createPublicKey(public_key)
26 var is_valid = crt.hashAndVerify('sha256', new Buffer(raw_data).toString('hex'), hex_signature, 'hex')
27 return is_valid
28 }
29
30 function createCertsIfNotExist (callback) {
31 certsExist(function (exist) {
32 if (exist === true) {
33 return callback(null)
34 }
35
36 createCerts(function (err) {
37 return callback(err)
38 })
39 })
40 }
41
42 function decrypt (key, data, callback) {
43 fs.readFile(getCertDir() + 'peertube.key.pem', function (err, file) {
44 if (err) return callback(err)
45
46 var my_private_key = ursa.createPrivateKey(file)
47 var decrypted_key = my_private_key.decrypt(key, 'hex', 'utf8')
48 var decrypted_data = symetricDecrypt(data, decrypted_key)
49
50 return callback(null, decrypted_data)
51 })
52 }
53
54 function encrypt (public_key, data, callback) {
55 var crt = ursa.createPublicKey(public_key)
56
57 symetricEncrypt(data, function (err, dataEncrypted) {
58 if (err) return callback(err)
59
60 var key = crt.encrypt(dataEncrypted.password, 'utf8', 'hex')
61 var encrypted = {
62 data: dataEncrypted.crypted,
63 key: key
64 }
65
66 callback(null, encrypted)
67 })
68 }
69
70 function getCertDir () {
71 return certDir
72 }
73
74 function sign (data) {
75 var myKey = ursa.createPrivateKey(fs.readFileSync(certDir + 'peertube.key.pem'))
76 var signature = myKey.hashAndSign('sha256', data, 'utf8', 'hex')
77
78 return signature
79 }
80
81 // ---------------------------------------------------------------------------
82
83 module.exports = peertubeCrypto
84
85 // ---------------------------------------------------------------------------
86
87 function certsExist (callback) {
88 fs.exists(certDir + 'peertube.key.pem', function (exists) {
89 return callback(exists)
90 })
91 }
92
93 function createCerts (callback) {
94 certsExist(function (exist) {
95 if (exist === true) {
96 var string = 'Certs already exist.'
97 logger.warning(string)
98 return callback(new Error(string))
99 }
100
101 logger.info('Generating a RSA key...')
102 openssl.exec('genrsa', { 'out': certDir + 'peertube.key.pem', '2048': false }, function (err) {
103 if (err) {
104 logger.error('Cannot create private key on this pod.', { error: err })
105 return callback(err)
106 }
107 logger.info('RSA key generated.')
108
109 logger.info('Manage public key...')
110 openssl.exec('rsa', { 'in': certDir + 'peertube.key.pem', 'pubout': true, 'out': certDir + 'peertube.pub' }, function (err) {
111 if (err) {
112 logger.error('Cannot create public key on this pod .', { error: err })
113 return callback(err)
114 }
115
116 logger.info('Public key managed.')
117 return callback(null)
118 })
119 })
120 })
121 }
122
123 function generatePassword (callback) {
124 crypto.randomBytes(32, function (err, buf) {
125 if (err) {
126 return callback(err)
127 }
128
129 callback(null, buf.toString('utf8'))
130 })
131 }
132
133 function symetricDecrypt (text, password) {
134 var decipher = crypto.createDecipher(algorithm, password)
135 var dec = decipher.update(text, 'hex', 'utf8')
136 dec += decipher.final('utf8')
137 return dec
138 }
139
140 function symetricEncrypt (text, callback) {
141 generatePassword(function (err, password) {
142 if (err) {
143 return callback(err)
144 }
145
146 var cipher = crypto.createCipher(algorithm, password)
147 var crypted = cipher.update(text, 'utf8', 'hex')
148 crypted += cipher.final('hex')
149 callback(null, { crypted: crypted, password: password })
150 })
151 }
152})()
diff --git a/helpers/requests.js b/helpers/requests.js
new file mode 100644
index 000000000..0e301da79
--- /dev/null
+++ b/helpers/requests.js
@@ -0,0 +1,111 @@
1;(function () {
2 'use strict'
3
4 var async = require('async')
5 var config = require('config')
6 var request = require('request')
7 var replay = require('request-replay')
8
9 var constants = require('../initializers/constants')
10 var logger = require('./logger')
11 var peertubeCrypto = require('./peertubeCrypto')
12
13 var http = config.get('webserver.https') ? 'https' : 'http'
14 var host = config.get('webserver.host')
15 var port = config.get('webserver.port')
16
17 var requests = {
18 makeMultipleRetryRequest: makeMultipleRetryRequest
19 }
20
21 function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
22 if (!callback) {
23 callback = callbackEach
24 callbackEach = null
25 }
26
27 var url = http + '://' + host + ':' + port
28 var signature
29
30 // Add signature if it is specified in the params
31 if (all_data.method === 'POST' && all_data.data && all_data.sign === true) {
32 signature = peertubeCrypto.sign(url)
33 }
34
35 // Make a request for each pod
36 async.each(pods, function (pod, callback_each_async) {
37 function callbackEachRetryRequest (err, response, body, url, pod) {
38 if (callbackEach !== null) {
39 callbackEach(err, response, body, url, pod, function () {
40 callback_each_async()
41 })
42 } else {
43 callback_each_async()
44 }
45 }
46
47 var params = {
48 url: pod.url + all_data.path,
49 method: all_data.method
50 }
51
52 // Add data with POST requst ?
53 if (all_data.method === 'POST' && all_data.data) {
54 // Encrypt data ?
55 if (all_data.encrypt === true) {
56 // TODO: ES6 with let
57 ;(function (copy_params, copy_url, copy_pod, copy_signature) {
58 peertubeCrypto.encrypt(pod.publicKey, JSON.stringify(all_data.data), function (err, encrypted) {
59 if (err) return callback(err)
60
61 copy_params.json = {
62 data: encrypted.data,
63 key: encrypted.key
64 }
65
66 makeRetryRequest(copy_params, copy_url, copy_pod, copy_signature, callbackEachRetryRequest)
67 })
68 })(params, url, pod, signature)
69 } else {
70 params.json = { data: all_data.data }
71 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
72 }
73 } else {
74 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
75 }
76 }, callback)
77 }
78
79 // ---------------------------------------------------------------------------
80
81 module.exports = requests
82
83 // ---------------------------------------------------------------------------
84
85 function makeRetryRequest (params, from_url, to_pod, signature, callbackEach) {
86 // Append the signature
87 if (signature) {
88 params.json.signature = {
89 url: from_url,
90 signature: signature
91 }
92 }
93
94 logger.debug('Make retry requests to %s.', to_pod.url)
95
96 replay(
97 request.post(params, function (err, response, body) {
98 callbackEach(err, response, body, params.url, to_pod)
99 }),
100 {
101 retries: constants.REQUEST_RETRIES,
102 factor: 3,
103 maxTimeout: Infinity,
104 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
105 }
106 ).on('replay', function (replay) {
107 logger.info('Replaying request to %s. Request failed: %d %s. Replay number: #%d. Will retry in: %d ms.',
108 params.url, replay.error.code, replay.error.message, replay.number, replay.delay)
109 })
110 }
111})()
diff --git a/helpers/utils.js b/helpers/utils.js
index ec46631b1..bd0557977 100644
--- a/helpers/utils.js
+++ b/helpers/utils.js
@@ -1,178 +1,10 @@
1;(function () { 1;(function () {
2 'use strict' 2 'use strict'
3 3
4 var async = require('async')
5 var config = require('config')
6 var crypto = require('crypto')
7 var fs = require('fs')
8 var openssl = require('openssl-wrapper')
9 var request = require('request')
10 var replay = require('request-replay')
11 var ursa = require('ursa')
12
13 var constants = require('../initializers/constants')
14 var logger = require('./logger') 4 var logger = require('./logger')
15 5
16 var certDir = __dirname + '/../' + config.get('storage.certs')
17 var http = config.get('webserver.https') ? 'https' : 'http'
18 var host = config.get('webserver.host')
19 var port = config.get('webserver.port')
20 var algorithm = 'aes-256-ctr'
21
22 var utils = { 6 var utils = {
23 getCertDir: getCertDir, 7 cleanForExit: cleanForExit
24 certsExist: certsExist,
25 cleanForExit: cleanForExit,
26 createCerts: createCerts,
27 createCertsIfNotExist: createCertsIfNotExist,
28 generatePassword: generatePassword,
29 makeMultipleRetryRequest: makeMultipleRetryRequest,
30 symetricEncrypt: symetricEncrypt,
31 symetricDecrypt: symetricDecrypt
32 }
33
34 function getCertDir () {
35 return certDir
36 }
37
38 function makeMultipleRetryRequest (all_data, pods, callbackEach, callback) {
39 if (!callback) {
40 callback = callbackEach
41 callbackEach = null
42 }
43
44 var url = http + '://' + host + ':' + port
45 var signature
46
47 // Add signature if it is specified in the params
48 if (all_data.method === 'POST' && all_data.data && all_data.sign === true) {
49 var myKey = ursa.createPrivateKey(fs.readFileSync(certDir + 'peertube.key.pem'))
50 signature = myKey.hashAndSign('sha256', url, 'utf8', 'hex')
51 }
52
53 // Make a request for each pod
54 async.each(pods, function (pod, callback_each_async) {
55 function callbackEachRetryRequest (err, response, body, url, pod) {
56 if (callbackEach !== null) {
57 callbackEach(err, response, body, url, pod, function () {
58 callback_each_async()
59 })
60 } else {
61 callback_each_async()
62 }
63 }
64
65 var params = {
66 url: pod.url + all_data.path,
67 method: all_data.method
68 }
69
70 // Add data with POST requst ?
71 if (all_data.method === 'POST' && all_data.data) {
72 // Encrypt data ?
73 if (all_data.encrypt === true) {
74 var crt = ursa.createPublicKey(pod.publicKey)
75
76 // TODO: ES6 with let
77 ;(function (crt_copy, copy_params, copy_url, copy_pod, copy_signature) {
78 symetricEncrypt(JSON.stringify(all_data.data), function (err, dataEncrypted) {
79 if (err) throw err
80
81 var passwordEncrypted = crt_copy.encrypt(dataEncrypted.password, 'utf8', 'hex')
82 copy_params.json = {
83 data: dataEncrypted.crypted,
84 key: passwordEncrypted
85 }
86
87 makeRetryRequest(copy_params, copy_url, copy_pod, copy_signature, callbackEachRetryRequest)
88 })
89 })(crt, params, url, pod, signature)
90 } else {
91 params.json = { data: all_data.data }
92 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
93 }
94 } else {
95 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
96 }
97 }, callback)
98 }
99
100 function certsExist (callback) {
101 fs.exists(certDir + 'peertube.key.pem', function (exists) {
102 return callback(exists)
103 })
104 }
105
106 function createCerts (callback) {
107 certsExist(function (exist) {
108 if (exist === true) {
109 var string = 'Certs already exist.'
110 logger.warning(string)
111 return callback(new Error(string))
112 }
113
114 logger.info('Generating a RSA key...')
115 openssl.exec('genrsa', { 'out': certDir + 'peertube.key.pem', '2048': false }, function (err) {
116 if (err) {
117 logger.error('Cannot create private key on this pod.', { error: err })
118 return callback(err)
119 }
120 logger.info('RSA key generated.')
121
122 logger.info('Manage public key...')
123 openssl.exec('rsa', { 'in': certDir + 'peertube.key.pem', 'pubout': true, 'out': certDir + 'peertube.pub' }, function (err) {
124 if (err) {
125 logger.error('Cannot create public key on this pod .', { error: err })
126 return callback(err)
127 }
128
129 logger.info('Public key managed.')
130 return callback(null)
131 })
132 })
133 })
134 }
135
136 function createCertsIfNotExist (callback) {
137 certsExist(function (exist) {
138 if (exist === true) {
139 return callback(null)
140 }
141
142 createCerts(function (err) {
143 return callback(err)
144 })
145 })
146 }
147
148 function generatePassword (callback) {
149 crypto.randomBytes(32, function (err, buf) {
150 if (err) {
151 return callback(err)
152 }
153
154 callback(null, buf.toString('utf8'))
155 })
156 }
157
158 function symetricEncrypt (text, callback) {
159 generatePassword(function (err, password) {
160 if (err) {
161 return callback(err)
162 }
163
164 var cipher = crypto.createCipher(algorithm, password)
165 var crypted = cipher.update(text, 'utf8', 'hex')
166 crypted += cipher.final('hex')
167 callback(null, { crypted: crypted, password: password })
168 })
169 }
170
171 function symetricDecrypt (text, password) {
172 var decipher = crypto.createDecipher(algorithm, password)
173 var dec = decipher.update(text, 'hex', 'utf8')
174 dec += decipher.final('utf8')
175 return dec
176 } 8 }
177 9
178 function cleanForExit (webtorrent_process) { 10 function cleanForExit (webtorrent_process) {
@@ -183,33 +15,4 @@
183 // --------------------------------------------------------------------------- 15 // ---------------------------------------------------------------------------
184 16
185 module.exports = utils 17 module.exports = utils
186
187 // ---------------------------------------------------------------------------
188
189 function makeRetryRequest (params, from_url, to_pod, signature, callbackEach) {
190 // Append the signature
191 if (signature) {
192 params.json.signature = {
193 url: from_url,
194 signature: signature
195 }
196 }
197
198 logger.debug('Make retry requests to %s.', to_pod.url)
199
200 replay(
201 request.post(params, function (err, response, body) {
202 callbackEach(err, response, body, params.url, to_pod)
203 }),
204 {
205 retries: constants.REQUEST_RETRIES,
206 factor: 3,
207 maxTimeout: Infinity,
208 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
209 }
210 ).on('replay', function (replay) {
211 logger.info('Replaying request to %s. Request failed: %d %s. Replay number: #%d. Will retry in: %d ms.',
212 params.url, replay.error.code, replay.error.message, replay.number, replay.delay)
213 })
214 }
215})() 18})()
diff --git a/lib/friends.js b/lib/friends.js
index e093c85c4..b0086a38b 100644
--- a/lib/friends.js
+++ b/lib/friends.js
@@ -8,10 +8,11 @@
8 8
9 var constants = require('../initializers/constants') 9 var constants = require('../initializers/constants')
10 var logger = require('../helpers/logger') 10 var logger = require('../helpers/logger')
11 var peertubeCrypto = require('../helpers/peertubeCrypto')
11 var Pods = require('../models/pods') 12 var Pods = require('../models/pods')
12 var PoolRequests = require('../models/poolRequests') 13 var PoolRequests = require('../models/poolRequests')
13 var poolRequests = require('../lib/poolRequests') 14 var poolRequests = require('../lib/poolRequests')
14 var utils = require('../helpers/utils') 15 var requests = require('../helpers/requests')
15 var Videos = require('../models/videos') 16 var Videos = require('../models/videos')
16 17
17 var http = config.get('webserver.https') ? 'https' : 'http' 18 var http = config.get('webserver.https') ? 'https' : 'http'
@@ -48,7 +49,7 @@
48 var pods_score = {} 49 var pods_score = {}
49 50
50 logger.info('Make friends!') 51 logger.info('Make friends!')
51 fs.readFile(utils.getCertDir() + 'peertube.pub', 'utf8', function (err, cert) { 52 fs.readFile(peertubeCrypto.getCertDir() + 'peertube.pub', 'utf8', function (err, cert) {
52 if (err) { 53 if (err) {
53 logger.error('Cannot read public cert.', { error: err }) 54 logger.error('Cannot read public cert.', { error: err })
54 return callback(err) 55 return callback(err)
@@ -115,7 +116,7 @@
115 videos: videos_list 116 videos: videos_list
116 } 117 }
117 118
118 utils.makeMultipleRetryRequest( 119 requests.makeMultipleRetryRequest(
119 { method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/', data: data }, 120 { method: 'POST', path: '/api/' + constants.API_VERSION + '/pods/', data: data },
120 121
121 pods_list, 122 pods_list,
@@ -176,7 +177,7 @@
176 } 177 }
177 178
178 // Announce we quit them 179 // Announce we quit them
179 utils.makeMultipleRetryRequest(request, pods, function () { 180 requests.makeMultipleRetryRequest(request, pods, function () {
180 Pods.removeAll(function (err) { 181 Pods.removeAll(function (err) {
181 poolRequests.activate() 182 poolRequests.activate()
182 183
diff --git a/lib/poolRequests.js b/lib/poolRequests.js
index 796f06149..f4ab434ad 100644
--- a/lib/poolRequests.js
+++ b/lib/poolRequests.js
@@ -8,7 +8,7 @@
8 var logger = require('../helpers/logger') 8 var logger = require('../helpers/logger')
9 var Pods = require('../models/pods') 9 var Pods = require('../models/pods')
10 var PoolRequests = require('../models/poolRequests') 10 var PoolRequests = require('../models/poolRequests')
11 var utils = require('../helpers/utils') 11 var requests = require('../helpers/requests')
12 var Videos = require('../models/videos') 12 var Videos = require('../models/videos')
13 13
14 var timer = null 14 var timer = null
@@ -40,7 +40,7 @@
40 40
41 // --------------------------------------------------------------------------- 41 // ---------------------------------------------------------------------------
42 42
43 function makePoolRequest (type, requests, callback) { 43 function makePoolRequest (type, requests_to_make, callback) {
44 if (!callback) callback = function () {} 44 if (!callback) callback = function () {}
45 45
46 Pods.list(function (err, pods) { 46 Pods.list(function (err, pods) {
@@ -51,7 +51,7 @@
51 sign: true, 51 sign: true,
52 method: 'POST', 52 method: 'POST',
53 path: null, 53 path: null,
54 data: requests 54 data: requests_to_make
55 } 55 }
56 56
57 if (type === 'add') { 57 if (type === 'add') {
@@ -65,7 +65,7 @@
65 var bad_pods = [] 65 var bad_pods = []
66 var good_pods = [] 66 var good_pods = []
67 67
68 utils.makeMultipleRetryRequest(params, pods, callbackEachPodFinished, callbackAllPodsFinished) 68 requests.makeMultipleRetryRequest(params, pods, callbackEachPodFinished, callbackAllPodsFinished)
69 69
70 function callbackEachPodFinished (err, response, body, url, pod, callback_each_pod_finished) { 70 function callbackEachPodFinished (err, response, body, url, pod, callback_each_pod_finished) {
71 if (err || (response.statusCode !== 200 && response.statusCode !== 204)) { 71 if (err || (response.statusCode !== 200 && response.statusCode !== 204)) {
@@ -95,7 +95,7 @@
95 95
96 if (pool_requests.length === 0) return 96 if (pool_requests.length === 0) return
97 97
98 var requests = { 98 var requests_to_make = {
99 add: { 99 add: {
100 ids: [], 100 ids: [],
101 requests: [] 101 requests: []
@@ -108,11 +108,11 @@
108 108
109 async.each(pool_requests, function (pool_request, callback_each) { 109 async.each(pool_requests, function (pool_request, callback_each) {
110 if (pool_request.type === 'add') { 110 if (pool_request.type === 'add') {
111 requests.add.requests.push(pool_request.request) 111 requests_to_make.add.requests.push(pool_request.request)
112 requests.add.ids.push(pool_request._id) 112 requests_to_make.add.ids.push(pool_request._id)
113 } else if (pool_request.type === 'remove') { 113 } else if (pool_request.type === 'remove') {
114 requests.remove.requests.push(pool_request.request) 114 requests_to_make.remove.requests.push(pool_request.request)
115 requests.remove.ids.push(pool_request._id) 115 requests_to_make.remove.ids.push(pool_request._id)
116 } else { 116 } else {
117 throw new Error('Unkown pool request type.') 117 throw new Error('Unkown pool request type.')
118 } 118 }
@@ -120,20 +120,20 @@
120 callback_each() 120 callback_each()
121 }, function () { 121 }, function () {
122 // Send the add requests 122 // Send the add requests
123 if (requests.add.requests.length !== 0) { 123 if (requests_to_make.add.requests.length !== 0) {
124 makePoolRequest('add', requests.add.requests, function (err) { 124 makePoolRequest('add', requests_to_make.add.requests, function (err) {
125 if (err) logger.error('Errors when sent add pool requests.', { error: err }) 125 if (err) logger.error('Errors when sent add pool requests.', { error: err })
126 126
127 PoolRequests.removeRequests(requests.add.ids) 127 PoolRequests.removeRequests(requests_to_make.add.ids)
128 }) 128 })
129 } 129 }
130 130
131 // Send the remove requests 131 // Send the remove requests
132 if (requests.remove.requests.length !== 0) { 132 if (requests_to_make.remove.requests.length !== 0) {
133 makePoolRequest('remove', requests.remove.requests, function (err) { 133 makePoolRequest('remove', requests_to_make.remove.requests, function (err) {
134 if (err) logger.error('Errors when sent remove pool requests.', { error: err }) 134 if (err) logger.error('Errors when sent remove pool requests.', { error: err })
135 135
136 PoolRequests.removeRequests(requests.remove.ids) 136 PoolRequests.removeRequests(requests_to_make.remove.ids)
137 }) 137 })
138 } 138 }
139 }) 139 })
diff --git a/middlewares/secure.js b/middlewares/secure.js
index 99ac9cdae..b7a18ad3e 100644
--- a/middlewares/secure.js
+++ b/middlewares/secure.js
@@ -1,12 +1,9 @@
1;(function () { 1;(function () {
2 'use strict' 2 'use strict'
3 3
4 var fs = require('fs')
5 var ursa = require('ursa')
6
7 var logger = require('../helpers/logger') 4 var logger = require('../helpers/logger')
5 var peertubeCrypto = require('../helpers/peertubeCrypto')
8 var Pods = require('../models/pods') 6 var Pods = require('../models/pods')
9 var utils = require('../helpers/utils')
10 7
11 var secureMiddleware = { 8 var secureMiddleware = {
12 decryptBody: decryptBody 9 decryptBody: decryptBody
@@ -27,20 +24,24 @@
27 24
28 logger.debug('Decrypting body from %s.', url) 25 logger.debug('Decrypting body from %s.', url)
29 26
30 var crt = ursa.createPublicKey(pod.publicKey) 27 var signature_ok = peertubeCrypto.checkSignature(pod.publicKey, url, req.body.signature.signature)
31 var signature_ok = crt.hashAndVerify('sha256', new Buffer(req.body.signature.url).toString('hex'), req.body.signature.signature, 'hex')
32 28
33 if (signature_ok === true) { 29 if (signature_ok === true) {
34 var myKey = ursa.createPrivateKey(fs.readFileSync(utils.getCertDir() + 'peertube.key.pem')) 30 peertubeCrypto.decrypt(req.body.key, req.body.data, function (err, decrypted) {
35 var decryptedKey = myKey.decrypt(req.body.key, 'hex', 'utf8') 31 if (err) {
36 req.body.data = JSON.parse(utils.symetricDecrypt(req.body.data, decryptedKey)) 32 logger.error('Cannot decrypt data.', { error: err })
37 delete req.body.key 33 return res.sendStatus(500)
34 }
35
36 req.body.data = JSON.parse(decrypted)
37 delete req.body.key
38
39 next()
40 })
38 } else { 41 } else {
39 logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.url) 42 logger.error('Signature is not okay in decryptBody for %s.', req.body.signature.url)
40 return res.sendStatus(403) 43 return res.sendStatus(403)
41 } 44 }
42
43 next()
44 }) 45 })
45 } 46 }
46 47
diff --git a/server.js b/server.js
index 1153c9ef6..b8674b0b5 100644
--- a/server.js
+++ b/server.js
@@ -32,6 +32,7 @@
32 var customValidators = require('./helpers/customValidators') 32 var customValidators = require('./helpers/customValidators')
33 var database = require('./initializers/database') 33 var database = require('./initializers/database')
34 var logger = require('./helpers/logger') 34 var logger = require('./helpers/logger')
35 var peertubeCrypto = require('./helpers/peertubeCrypto')
35 var poolRequests = require('./lib/poolRequests') 36 var poolRequests = require('./lib/poolRequests')
36 var routes = require('./controllers') 37 var routes = require('./controllers')
37 var utils = require('./helpers/utils') 38 var utils = require('./helpers/utils')
@@ -117,7 +118,7 @@
117 // Prod : no stacktraces leaked to user 118 // Prod : no stacktraces leaked to user
118 if (process.env.NODE_ENV === 'production') { 119 if (process.env.NODE_ENV === 'production') {
119 app.use(function (err, req, res, next) { 120 app.use(function (err, req, res, next) {
120 logger.error('Error : ' + err.message, { error: err }) 121 logger.error(err)
121 res.status(err.status || 500) 122 res.status(err.status || 500)
122 res.render('error', { 123 res.render('error', {
123 message: err.message, 124 message: err.message,
@@ -126,7 +127,7 @@
126 }) 127 })
127 } else { 128 } else {
128 app.use(function (err, req, res, next) { 129 app.use(function (err, req, res, next) {
129 logger.error('Error : ' + err.message, { error: err }) 130 logger.error(err)
130 res.status(err.status || 500) 131 res.status(err.status || 500)
131 res.render('error', { 132 res.render('error', {
132 message: err.message, 133 message: err.message,
@@ -136,7 +137,7 @@
136 } 137 }
137 138
138 // ----------- Create the certificates if they don't already exist ----------- 139 // ----------- Create the certificates if they don't already exist -----------
139 utils.createCertsIfNotExist(function (err) { 140 peertubeCrypto.createCertsIfNotExist(function (err) {
140 if (err) throw err 141 if (err) throw err
141 // Create/activate the webtorrent module 142 // Create/activate the webtorrent module
142 webtorrent.create(function () { 143 webtorrent.create(function () {