Advertisement
Guest User

Untitled

a guest
Mar 31st, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.82 KB | None | 0 0
  1. var net = require('net')
  2. , encryption = require('./../encryption')
  3. , ursa = require('ursa')
  4. , exec = require('child_process').exec
  5. , fs = require('fs')
  6. , sh = require('execSync')
  7.  
  8. var stdin = process.openStdin()
  9.  
  10. var username, password, connection, privateKey, publicKey, otherPublicKey = false, userNames = [], certificate = false, myId, isNew = true
  11.  
  12. privateKey = ursa.generatePrivateKey()
  13. publicKey = privateKey.toPublicPem().toString()
  14.  
  15. fs.writeFileSync('private-key.pem', privateKey.toPrivatePem().toString())
  16.  
  17. /**************
  18. GENERATING CERTIFICATE REQUEST AND SENDING IT TO THE CERTIFICATE AUTHOROTY
  19. ***************/
  20. sh.exec("openssl req -new -key private-key.pem -out request.pem -subj /C=SY/ST=Syria/L=Damascus/O=A/emailAddress=a@a.com")
  21. var request = fs.readFileSync('request.pem').toString()
  22.  
  23. var caServer = net.connect(5000, function(){
  24. caServer.write(request)
  25. caServer.on('data', function(data){
  26. //getting certificate
  27. var res = sh.exec('openssl x509 -req -in request.pem -signkey private-key.pem -out certificate.pem')
  28. certificate = fs.readFileSync('certificate.pem').toString()
  29. //AFTER WE GET A CERTIFICATE, WE CONNECT TO THE CHAT SERVER
  30. connectServer()
  31. })
  32. })
  33.  
  34.  
  35. var receiveId = false
  36. var otherPublicKeys = []
  37. var sessionKey = 'asdf'
  38.  
  39. //THIS FUNCTION IS USED TO INITIALIZE THE CONNECTION BETWEEN THE CLIENT AND SERVER
  40. function initialization(){
  41. //WE FIRST SEND THE PUBLIC KEY TO THE SERVER
  42. connection.write(publicKey)
  43.  
  44. //THEN WE GET INPUT FROM THE USER
  45. console.log('Please enter your username!')
  46. stdin.addListener('data', function(data){
  47. //WE RECEIVE THE USERNAME
  48. if (!username){
  49. username = data
  50. connection.write(username)
  51. console.log('Please enter your password')
  52. //THEN WE RECEIVE THE PASSWORD AND SEND IT
  53. } else if (!password) {
  54. password = data
  55. connection.write(password)
  56. //THEN WE FINALLY START SENDING DATA ENCRYPTED WITH THE SESSION KEY, ATTACHED WITH OUR ID AND OUR SIGNITURE
  57. //FORMAT: [signiature:userId:encryptedMessage]
  58. } else {
  59. connection.write(encryption.sign(data, privateKey) + ':' + myId.toString() + ':' +encryption.encryptAES(data, sessionKey))
  60. }
  61. })
  62. }
  63.  
  64. /*
  65. FUNCTION TO PROCESS INCOMING DATA
  66. WE HAVE 4 BASIC INCOMING
  67.  
  68. 1) PUBLIC KEYS
  69. whenever a new user joins the chat group, we send his public key to all other connecting clients
  70. so that these clients can use this key to verify the digital signed messages sent by this client
  71. each public key is attached with the client id that it belongs to in addition to the username of
  72. this client
  73.  
  74. Multiple keys are sent in the following format
  75.  
  76. -----BEGIN PUBLIC KEY-----
  77. XXXXXXXXXXXXXXXXXXXXXXXXX
  78. -----END PUBLIC KEY-----
  79. username1
  80. -----END PUBLIC KEY-----
  81. id1
  82.  
  83. -----BEGIN PUBLIC KEY-----
  84. YYYYYYYYYYYYYYYYYYYYYYYYYY
  85. -----END PUBLIC KEY-----
  86. username2
  87. -----END PUBLIC KEY-----
  88. id2
  89.  
  90.  
  91. ====
  92.  
  93. 2) SESSION KEY
  94. whever a new client joins the chat group, his is sent a sessionKey that he should use to encrypt
  95. that he should use to encrypt and decrypt all outgoing and incoming messages
  96.  
  97. 3) CLIENT ID
  98. each client has a unique id that he receives from the server. if the client has an id of 0, then
  99. he is the first client , and he is responsible for generating and distributing the sessino key
  100.  
  101. 4) CHAT MESSAGES
  102. after the chat user finally gets the session key, he starts sending and receiveing chat message.
  103. each message is composed of three parts: [signiture:userId:encryptedMessage]
  104.  
  105.  
  106. */
  107. function input(data){
  108.  
  109.  
  110.  
  111. var parsed = data.toString()
  112. var type = parsed.substring(0, 3)
  113. var string = parsed.substring(3, parsed.length)
  114.  
  115. if (type === 'pub'){
  116.  
  117. string.split('-----BEGIN PUBLIC KEY-----\n').forEach(function(message){
  118.  
  119. if (message.length > 1){
  120. var isCertificate = true
  121. var isName = true
  122. var key, receivedIndex, receivedName
  123.  
  124. message.split('-----END PUBLIC KEY-----\n').forEach(function(message){
  125.  
  126. if (isCertificate){
  127.  
  128. message = '-----BEGIN PUBLIC KEY-----\n' + message + '-----END PUBLIC KEY-----\n'
  129. key = ursa.createPublicKey(message)
  130. isCertificate = false
  131.  
  132. } else if (isName) {
  133. receivedName = message
  134. isName = false
  135. } else {
  136. receivedIndex = parseInt(message)
  137. otherPublicKeys[receivedIndex] = key
  138. userNames[receivedIndex] = receivedName
  139. isCertificate = true
  140. isName = true
  141. }
  142. })
  143.  
  144. console.log('========================================')
  145. console.log('SERVER: receiving key of client ' + receivedIndex)
  146. console.log(key.toPublicPem().toString().slice(0, -1))
  147. console.log('========================================')
  148.  
  149. //IF I AM THE SESSION ADMIN, I SHOULD SEND THE SESSION KEY TO THE NEW CONNECTING CLIENT
  150. if (myId == 0 && receivedIndex != 0){
  151. connection.write('sessionKey:' + receivedIndex + ':'+ encryption.encrypt(sessionKey, key))
  152. }
  153.  
  154. }
  155. })
  156.  
  157.  
  158. } else if (parsed.indexOf('sessionKey') >= 0){
  159.  
  160. var result = string.split(':')
  161. sessionKey = encryption.decrypt(result[2], privateKey)
  162.  
  163. console.log('========================================')
  164. console.log('SERVER: receiving session key: ' + sessionKey)
  165. console.log('========================================')
  166.  
  167.  
  168. } else if (isNew) {
  169.  
  170. myId = parseInt(data.toString())
  171. console.log('SERVER: Your ID is: '+myId)
  172. isNew = false
  173.  
  174. } else {
  175.  
  176. var triple = data.toString().split(':') //converting the received buffer to a string
  177. var signiture = triple[0]
  178. var userId = parseInt(triple[1])
  179. var string = triple[2]
  180.  
  181. var decryptedString = encryption.decryptAES(string, sessionKey)
  182.  
  183. if (encryption.verify(decryptedString, signiture, otherPublicKeys[userId])){
  184. //removing /n character
  185. console.log("| " + userNames[userId] + ': ' + decryptedString.substr(0, decryptedString.length-1))
  186.  
  187. } else {
  188. console.log('Error! The sent string has been changed!!!')
  189. }
  190.  
  191. }
  192. }
  193.  
  194. function connectServer(){
  195. connection = net.connect(4000, "localhost", initialization)
  196. connection.on('data', input)
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement