예제 #1
0
    def start(self):
        #from libs.svhelper import ,getCredentials,getRealm,getCID
        import socket, pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip,self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:            
                self.sock.bind((self.bindingip,self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1            
        if self.originallocalport != self.localport:
            self.log.warn("could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead" % (self.bindingip,self.originallocalport, self.localport))
            self.log.info("Make use of the -P option to specify a port to bind to yourself")

        # perform a test 1st ..
        data = self.Register(self.extension,self.domain)
        try:
            mysendto(self.sock,data,(self.dsthost,self.dstport))
        except socket.error,err:
            self.log.error("socket error: %s" % err)
            return
예제 #2
0
    def start(self):        
        import socket, pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip,self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip,self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warn("could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead" % (self.bindingip,self.originallocalport, self.localport))
            self.log.info("Make use of the -P option to specify a port to bind to yourself")

        # perform a test 1st .. we want to see if we get a 404
        # some other error for unknown users
        self.nextuser = random.getrandbits(32)
        data = self.createRequest(self.method,self.nextuser)
        try:
            mysendto(self.sock,data,(self.dsthost,self.dstport))
            #self.sock.sendto(data,(self.dsthost,self.dstport))
        except socket.error,err:
            self.log.error("socket error: %s" % err)
            return
예제 #3
0
    def start(self):
        #from libs.svhelper import ,getCredentials,getRealm,getCID
        import socket, pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip, self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip, self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warn(
                "could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead"
                % (self.bindingip, self.originallocalport, self.localport))
            self.log.info(
                "Make use of the -P option to specify a port to bind to yourself"
            )

        # perform a test 1st ..
        data = self.Register(self.extension, self.domain)
        try:
            mysendto(self.sock, data, (self.dsthost, self.dstport))
        except socket.error, err:
            self.log.error("socket error: %s" % err)
            return
예제 #4
0
    def start(self):
        """
        Method that start perfom some actions.

        :return:
        """
        #from libs.svhelper import ,getCredentials,getRealm,getCID
        import socket, pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip,self.localport))
        while 1:
            # Check if there any ports are available, print error message if not.
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                # Bind the socket to address. The socket must not already be bound.
                self.sock.bind((self.bindingip,self.localport))
                break
            # This exception is raised for socket-related errors. The accompanying value is either a string telling
            # what went wrong or a pair (errno, string) representing an error returned by a system call, similar
            # to the value accompanying os.error.
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1            
        if self.originallocalport != self.localport:
            self.log.warn("could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead" % (self.bindingip,self.originallocalport, self.localport))
            self.log.info("Make use of the -P option to specify a port to bind to yourself")

        # perform a test 1st ..
        # and try to register
        data = self.Register(self.extension,self.domain)
        try:
            mysendto(self.sock,data,(self.dsthost,self.dstport))
        except socket.error,err:
            self.log.error("socket error: %s" % err)
            return
예제 #5
0
    def start(self):
        import socket
        import pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip, self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip, self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warn(
                "could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead"
                % (self.bindingip, self.originallocalport, self.localport))
            self.log.info(
                "Make use of the -P option to specify a port to bind to yourself"
            )

        # perform a test 1st .. we want to see if we get a 404
        # some other error for unknown users
        self.nextuser = random.getrandbits(32)
        data = self.createRequest(self.method, self.nextuser)
        try:
            mysendto(self.sock, data, (self.dsthost, self.dstport))
            # self.sock.sendto(data,(self.dsthost,self.dstport))
        except socket.error, err:
            self.log.error("socket error: %s" % err)
            return
예제 #6
0
    def getResponse(self):
        from libs.svhelper import getNonce, getCredentials, getRealm, getCID, getTag
        from base64 import b64decode
        from libs.svhelper import parseHeader
        from libs.svhelper import mysendto
        import re
        # we got stuff to read off the socket
        from socket import error as socketerror
        buff, srcaddr = self.sock.recvfrom(8192)
        if self.printdebug:
            print srcaddr
            print buff

        try:
            extension = getTag(buff)
        except TypeError:
            self.log.error('could not decode to tag')
            extension = None
        if extension is None:
            self.nomore = True
            return
        try:
            firstline = buff.splitlines()[0]
        except (ValueError, IndexError, AttributeError):
            self.log.error("could not get the 1st line")
            return
        if self.enableack:
            # send an ack to any responses which match
            _tmp = parseHeader(buff)
            if not (_tmp and _tmp.has_key('code')):
                return
            if 699 > _tmp['code'] >= 200:
                self.log.debug('will try to send an ACK response')
                if not _tmp.has_key('headers'):
                    self.log.debug('no headers?')
                    return
                if not _tmp['headers'].has_key('from'):
                    self.log.debug('no from?')
                    return
                if not _tmp['headers'].has_key('cseq'):
                    self.log.debug('no cseq')
                    return
                if not _tmp['headers'].has_key('call-id'):
                    self.log.debug('no caller id')
                    return
                try:
                    username = getTag(
                        buff)  #_tmp['headers']['from'][0].split('"')[1]
                except IndexError:
                    self.log.warn('could not parse the from address %s' %
                                  _tmp['headers']['from'])
                    username = '******'
                cseq = _tmp['headers']['cseq'][0]
                cseqmethod = cseq.split()[1]
                if 'INVITE' == cseqmethod:
                    cid = _tmp['headers']['call-id'][0]
                    fromaddr = _tmp['headers']['from'][0]
                    toaddr = _tmp['headers']['to'][0]
                    ackreq = self.createRequest(
                        'ACK',
                        cid=cid,
                        cseq=cseq.replace(cseqmethod, ''),
                        fromaddr=fromaddr,
                        toaddr=toaddr,
                    )
                    self.log.debug('here is your ack request: %s' % ackreq)
                    mysendto(self.sock, ackreq, (self.dsthost, self.dstport))
                    #self.sock.sendto(ackreq,(self.dsthost,self.dstport))
                    if _tmp['code'] == 200:
                        byemsg = self.createRequest(
                            'BYE',
                            cid=cid,
                            cseq='2',
                            fromaddr=fromaddr,
                            toaddr=toaddr,
                        )
                        self.log.debug(
                            'sending a BYE to the 200 OK for the INVITE')
                        mysendto(self.sock, byemsg,
                                 (self.dsthost, self.dstport))

        if firstline != self.BADUSER:
            if buff.startswith(self.PROXYAUTHREQ) \
            or buff.startswith(self.INVALIDPASS) \
            or buff.startswith(self.AUTHREQ):
                if self.realm is None:
                    self.realm = getRealm(buff)
                self.log.info(
                    "extension '%s' exists - requires authentication" %
                    extension)
                self.resultauth[extension] = 'reqauth'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
            elif buff.startswith(self.TRYING):
                pass
            elif buff.startswith(self.RINGING):
                pass
            elif buff.startswith(self.OKEY):
                self.log.info(
                    "extension '%s' exists - authentication not required" %
                    extension)
                self.resultauth[extension] = 'noauth'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
            else:
                self.log.warn(
                    "extension '%s' probably exists but the response is unexpected"
                    % extension)
                self.log.debug("response: %s" % firstline)
                self.resultauth[extension] = 'weird'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
        elif buff.startswith(self.NOTFOUND):
            self.log.debug("User '%s' not found" % extension)
        elif buff.startswith(self.INEXISTENTTRANSACTION):
            pass

        # Prefix not found, lets go to the next one. Should we add a warning here???
        elif buff.startswith(self.SERVICEUN):
            pass
        elif buff.startswith(self.TRYING):
            pass
        elif buff.startswith(self.RINGING):
            pass
        elif buff.startswith(self.OKEY):
            pass
        elif buff.startswith(self.DECLINED):
            pass
        elif buff.startswith(self.NOTALLOWED):
            self.log.warn("method not allowed")
            self.nomore = True
            return
        elif buff.startswith(self.BADREQUEST):
            self.log.error(
                "Protocol / interopability error! The remote side most probably has problems with parsing your SIP messages!"
            )
            self.nomore = True
            return
        else:
            self.log.warn("We got an unknown response")
            self.log.error("Response: %s" % ` buff `)
            self.log.debug("1st line: %s" % ` firstline `)
            self.log.debug("Bad user: %s" % ` self.BADUSER `)
            self.nomore = True
예제 #7
0
         'It has been %s seconds since we last received a response - stopping'
         % timediff)
     continue
 # no stuff to read .. its our turn to send back something
 try:
     self.nextuser = self.usernamegen.next()
 except StopIteration:
     self.nomore = True
     continue
 except TypeError:
     self.nomore = True
     self.log.exception('Bad format string')
 data = self.createRequest(self.method, self.nextuser)
 try:
     self.log.debug("sending request for %s" % self.nextuser)
     mysendto(self.sock, data, (self.dsthost, self.dstport))
     #self.sock.sendto(data,(self.dsthost,self.dstport))
     if self.sessionpath is not None:
         if self.packetcount.next():
             try:
                 if self.guessmode == 1:
                     pickle.dump(
                         self.nextuser,
                         open(
                             os.path.join(
                                 exportpath,
                                 'lastextension.pkl'), 'w'))
                     self.log.debug('logged last extension %s' %
                                    self.nextuser)
                 elif self.guessmode == 2:
                     pickle.dump(
예제 #8
0
         self.auth['nonce'],cid = self.challenges.pop()
     self.auth['proxy'] = self.dstisproxy 
     try:                        
         self.auth['password'] = self.passwdgen.next()
         self.previouspassword = self.auth['password']
         self.log.debug('trying %s' % self.auth['password'])
     except StopIteration:
         self.log.info("no more passwords")
         self.nomore = True
         continue
 else:
     self.auth = None
     cid = None
 data = self.Register(self.extension,self.domain,self.auth,cid)                
 try:
     mysendto(self.sock,data,(self.dsthost,self.dstport))
     #self.sock.sendto(data,(self.dsthost,self.dstport))
     if self.sessionpath is not None:
         if self.packetcount.next():                    
             try:                                    
                 if self.crackmode == 1:
                     pickle.dump(self.previouspassword,open(os.path.join(self.sessionpath,'lastpasswd.pkl'),'w'))
                     self.log.debug('logged last extension %s' % self.previouspassword)
                 elif self.crackmode == 2:
                     pickle.dump(self.crackargs.tell(),open(os.path.join(self.sessionpath,'lastpasswd.pkl'),'w'))
                     self.log.debug('logged last position %s' % self.crackargs.tell())
             except IOError:
                 self.log.warn('could not log the last extension scanned')                    
 except socket.error,err:
     self.log.error("socket error: %s" % err)
     break
예제 #9
0
    def start(self):
        from libs.svhelper import makeRequest, createTag
        from libs.svhelper import mysendto
        import socket
        # bind to 5060 - the reason is to maximize compatability with
        # devices that disregard the source port and send replies back
        # to port 5060
        self.log.debug("binding to %s:%s" % (self.bindingip, self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip, self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warn(
                "could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead"
                % (self.bindingip, self.originallocalport, self.localport))
            self.log.info(
                "Make use of the -P option to specify a port to bind to yourself"
            )
        while 1:
            r, w, e = select.select(self.rlist, self.wlist, self.xlist,
                                    self.selecttime)
            if r:
                # we got stuff to read off the socket
                try:
                    buff, srcaddr = self.sock.recvfrom(8192)
                    self.log.debug('got data from %s:%s' % srcaddr)
                    self.log.debug('data: %s' % ` buff `)
                    if self.printdebug:
                        print srcaddr
                        print buff
                except socket.error:
                    continue
                self.getResponse(buff, srcaddr)
            else:
                # no stuff to read .. its our turn to send back something
                if self.nomoretoscan:
                    try:
                        # having the final sip
                        self.log.debug("Making sure that no packets get lost")
                        self.log.debug("Come to daddy")
                        while 1:
                            buff, srcaddr = self.sock.recvfrom(8192)
                            if self.printdebug:
                                print srcaddr
                                print buff
                            self.getResponse(buff, srcaddr)
                    except socket.error:
                        break
                try:
                    nextscan = self.scaniter.next()
                except StopIteration:
                    self.log.debug('no more hosts to scan')
                    self.nomoretoscan = True
                    continue
                dstip, dstport, method = nextscan
                self.nextip = dstip
                dsthost = (dstip, dstport)
                branchunique = '%s' % random.getrandbits(32)

                localtag = createTag('%s%s' % (''.join(
                    map(lambda x: '%02x' % int(x),
                        dsthost[0].split('.'))), '%04x' % dsthost[1]))
                cseq = 1
                fromaddr = '"%s"<%s>' % (self.fromname, self.fromaddr)
                toaddr = fromaddr
                callid = '%s' % random.getrandbits(80)
                contact = None
                if method != 'REGISTER':
                    contact = 'sip:%s@%s:%s' % (
                        self.extension, self.externalip, self.localport)
                data = makeRequest(method,
                                   fromaddr,
                                   toaddr,
                                   dsthost[0],
                                   dsthost[1],
                                   callid,
                                   self.externalip,
                                   branchunique,
                                   compact=self.compact,
                                   localtag=localtag,
                                   contact=contact,
                                   accept='application/sdp',
                                   localport=self.localport,
                                   extension=self.extension)
                try:
                    self.log.debug("sending packet to %s:%s" % dsthost)
                    self.log.debug("packet: %s" % ` data `)
                    mysendto(self.sock, data, dsthost)
                    self.sentpackets += 1
                    #self.sock.sendto(data,dsthost)
                    if self.sessionpath is not None:
                        if self.packetcount.next():
                            try:
                                f = open(
                                    os.path.join(self.sessionpath,
                                                 'lastip.pkl'), 'w')
                                pickle.dump(self.nextip, f)
                                f.close()
                                self.log.debug('logged last ip %s' %
                                               self.nextip)
                            except IOError:
                                self.log.warn(
                                    'could not log the last ip scanned')
                    if self.first is not None:
                        if self.sentpackets >= self.first:
                            self.log.info(
                                'Reached the limit to scan the first %s packets'
                                % self.first)
                            self.nomoretoscan = True
                except socket.error, err:
                    self.log.error(
                        "socket error while sending to %s:%s -> %s" %
                        (dsthost[0], dsthost[1], err))
                    pass
예제 #10
0
    def getResponse(self):
        from libs.svhelper import getNonce,getCredentials,getRealm,getCID,getTag        
        from base64 import b64decode
        from libs.svhelper import parseHeader
        from libs.svhelper import mysendto
        import re
        # we got stuff to read off the socket
        from socket import error as socketerror
        buff,srcaddr = self.sock.recvfrom(8192)
        if self.printdebug:
            print srcaddr
            print buff

        try:
            extension = getTag(buff)
        except TypeError:
            self.log.error('could not decode to tag')
            extension = None
        if extension is None:
            self.nomore = True
            return
        try:
            firstline = buff.splitlines()[0]
        except (ValueError,IndexError,AttributeError):
            self.log.error("could not get the 1st line")
            return
        if self.enableack:        
            # send an ack to any responses which match
            _tmp = parseHeader(buff)
            if not (_tmp and _tmp.has_key('code')):
                return
            if 699 > _tmp['code'] >= 200:
                self.log.debug('will try to send an ACK response')                
                if not _tmp.has_key('headers'):
                    self.log.debug('no headers?')
                    return
                if not _tmp['headers'].has_key('from'):
                    self.log.debug('no from?')
                    return
                if not _tmp['headers'].has_key('cseq'):
                    self.log.debug('no cseq')
                    return
                if not _tmp['headers'].has_key('call-id'):
                    self.log.debug('no caller id')
                    return
                try:
                    username = getTag(buff)#_tmp['headers']['from'][0].split('"')[1]
                except IndexError:
                    self.log.warn('could not parse the from address %s' % _tmp['headers']['from'])
                    username = '******'
                cseq = _tmp['headers']['cseq'][0]
                cseqmethod = cseq.split()[1]
                if 'INVITE' == cseqmethod:
                    cid = _tmp['headers']['call-id'][0]
                    fromaddr = _tmp['headers']['from'][0]
                    toaddr = _tmp['headers']['to'][0]
                    ackreq = self.createRequest('ACK',                                       
                                           cid=cid,
                                           cseq=cseq.replace(cseqmethod,''),
                                           fromaddr=fromaddr,
                                           toaddr=toaddr,
                                           )
                    self.log.debug('here is your ack request: %s' % ackreq)
                    mysendto(self.sock,ackreq,(self.dsthost,self.dstport))
                    #self.sock.sendto(ackreq,(self.dsthost,self.dstport))
                    if _tmp['code'] == 200:
                        byemsg = self.createRequest('BYE',
                                cid=cid,
                                cseq='2',
                                fromaddr=fromaddr,
                                toaddr=toaddr,
                                )
                        self.log.debug('sending a BYE to the 200 OK for the INVITE')
                        mysendto(self.sock,byemsg,(self.dsthost,self.dstport))

        if firstline != self.BADUSER:
            if buff.startswith(self.PROXYAUTHREQ) \
            or buff.startswith(self.INVALIDPASS) \
            or buff.startswith(self.AUTHREQ):
                if self.realm is None:
                    self.realm = getRealm(buff)
                self.log.info("extension '%s' exists - requires authentication" % extension)
                self.resultauth[extension] = 'reqauth'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
            elif buff.startswith(self.TRYING):
                pass
            elif buff.startswith(self.RINGING):
                pass
            elif buff.startswith(self.OKEY):
                self.log.info("extension '%s' exists - authentication not required" % extension)
                self.resultauth[extension] = 'noauth'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
            else:
                self.log.warn("extension '%s' probably exists but the response is unexpected" % extension)
                self.log.debug("response: %s" % firstline)
                self.resultauth[extension] = 'weird'
                if self.sessionpath is not None and self.dbsyncs:
                    self.resultauth.sync()
        elif buff.startswith(self.NOTFOUND):
            self.log.debug("User '%s' not found" % extension)
        elif buff.startswith(self.INEXISTENTTRANSACTION):
            pass
        
        # Prefix not found, lets go to the next one. Should we add a warning here???
        elif buff.startswith(self.SERVICEUN):
            pass
        elif buff.startswith(self.TRYING):
            pass
        elif buff.startswith(self.RINGING):
            pass
        elif buff.startswith(self.OKEY):
            pass
        elif buff.startswith(self.DECLINED):
            pass
        elif buff.startswith(self.NOTALLOWED):
            self.log.warn("method not allowed")
            self.nomore = True
            return
        elif buff.startswith(self.BADREQUEST):
            self.log.error("Protocol / interopability error! The remote side most probably has problems with parsing your SIP messages!")
            self.nomore = True
            return
        else:
            self.log.warn("We got an unknown response")
            self.log.error("Response: %s" % `buff`)
            self.log.debug("1st line: %s" % `firstline`)
            self.log.debug("Bad user: %s" % `self.BADUSER`)
            self.nomore = True
예제 #11
0
    def start(self):
        # from libs.svhelper import ,getCredentials,getRealm,getCID
        import socket
        import pickle
        from libs.svhelper import mysendto
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip, self.localport))
        while True:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip, self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warn(
                "could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead"
                % (self.bindingip, self.originallocalport, self.localport))
            self.log.info(
                "Make use of the -P option to specify a port to bind to yourself"
            )

        # perform a test 1st ..
        data = self.Register(self.extension, self.domain)
        try:
            mysendto(self.sock, data, (self.dsthost, self.dstport))
        except socket.error as err:
            self.log.error("socket error: %s" % err)
            return
        try:
            self.getResponse()
            self.lastrecvtime = time.time()
        except socket.timeout:
            self.log.error("no server response")
            return
        except socket.error as err:
            self.log.error("socket error:%s" % err)
            return
        if self.noauth is True:
            return
        while True:
            r, w, e = select.select(self.rlist, self.wlist, self.xlist,
                                    self.selecttime)
            if r:
                if self.passwordcracked:
                    break
                # we got stuff to read off the socket
                try:
                    self.getResponse()
                    self.lastrecvtime = time.time()
                except socket.error as err:
                    self.log.warn("socket error: %s" % err)
            else:
                # check if its been a while since we had a response to prevent
                # flooding - otherwise stop
                timediff = time.time() - self.lastrecvtime
                if timediff > self.maxlastrecvtime:
                    self.nomore = True
                    self.log.warn(
                        'It has been %s seconds since we last received a response - stopping'
                        % timediff)
                if self.passwordcracked:
                    break
                if self.nomore is True:
                    try:
                        while not self.passwordcracked:
                            self.getResponse()
                    except socket.timeout:
                        break
                # no stuff to read .. its our turn to send back something
                if len(self.challenges) > 0:
                    # we have challenges to take care of
                    self.auth = dict()
                    self.auth['username'] = self.username
                    self.auth['realm'] = self.realm
                    if self.reusenonce:
                        self.auth['nonce'] = self.staticnonce
                        cid = self.staticcid
                    else:
                        self.auth['nonce'], cid = self.challenges.pop()
                    self.auth['proxy'] = self.dstisproxy
                    try:
                        self.auth['password'] = next(self.passwdgen)
                        self.previouspassword = self.auth['password']
                        self.log.debug('trying %s' % self.auth['password'])
                    except StopIteration:
                        self.log.info("no more passwords")
                        self.nomore = True
                        continue
                else:
                    self.auth = None
                    cid = None
                data = self.Register(self.extension, self.domain, self.auth,
                                     cid)
                try:
                    mysendto(self.sock, data, (self.dsthost, self.dstport))
                    # self.sock.sendto(data,(self.dsthost,self.dstport))
                    if self.sessionpath is not None:
                        if next(self.packetcount):
                            try:
                                if self.crackmode == 1:
                                    pickle.dump(
                                        self.previouspassword,
                                        open(
                                            os.path.join(
                                                exportpath, 'lastpasswd.pkl'),
                                            'w'))
                                    self.log.debug('logged last extension %s' %
                                                   self.previouspassword)
                                elif self.crackmode == 2:
                                    pickle.dump(
                                        self.crackargs.tell(),
                                        open(
                                            os.path.join(
                                                exportpath, 'lastpasswd.pkl'),
                                            'w'))
                                    self.log.debug('logged last position %s' %
                                                   self.crackargs.tell())
                            except IOError:
                                self.log.warn(
                                    'could not log the last extension scanned')
                except socket.error as err:
                    self.log.error("socket error: %s" % err)
                    break
예제 #12
0
    def start(self):
        if self.bindingip == '':
            bindingip = 'any'
        else:
            bindingip = self.bindingip
        self.log.debug("binding to %s:%s" % (bindingip, self.localport))
        while 1:
            if self.localport > 65535:
                self.log.critical("Could not bind to any port")
                return
            try:
                self.sock.bind((self.bindingip, self.localport))
                break
            except socket.error:
                self.log.debug("could not bind to %s" % self.localport)
                self.localport += 1
        if self.originallocalport != self.localport:
            self.log.warning(
                "could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead"
                % (self.bindingip, self.originallocalport, self.localport))
            self.log.info(
                "Make use of the -P option to specify a port to bind to yourself"
            )

        # perform a test 1st .. we want to see if we get a 404
        # some other error for unknown users
        self.nextuser = random.getrandbits(32)
        data = self.createRequest(self.method, self.nextuser)
        try:
            mysendto(self.sock, data, (self.dsthost, self.dstport))
            # self.sock.sendto(data,(self.dsthost,self.dstport))
        except socket.error as err:
            self.log.error("socket error: %s" % err)
            return
        # first we identify the assumed reply for an unknown extension
        gotbadresponse = False
        try:
            while 1:
                try:
                    buff, srcaddr = self.sock.recvfrom(8192)
                    if self.printdebug:
                        print(srcaddr)
                        print(buff)
                except socket.error as err:
                    self.log.error("socket error: %s" % err)
                    return
                buff = buff.decode('utf-8', 'ignore')
                if buff.startswith(self.TRYING) \
                        or buff.startswith(self.RINGING) \
                        or buff.startswith(self.UNAVAILABLE):
                    gotbadresponse = True
                elif (buff.startswith(self.PROXYAUTHREQ)
                      or buff.startswith(self.INVALIDPASS)
                      or buff.startswith(self.AUTHREQ)) \
                        and self.initialcheck:
                    self.log.error(
                        "SIP server replied with an authentication request for an unknown extension. Set --force to force a scan."
                    )
                    return
                else:
                    self.BADUSER = buff.splitlines()[0]
                    self.log.debug("Bad user = %s" % self.BADUSER)
                    gotbadresponse = False
                    break
        except socket.timeout:
            if gotbadresponse:
                self.log.error("The response we got was not good: %s" %
                               buff.__repr__())
            else:
                self.log.error(
                    "No server response - are you sure that this PBX is listening? run svmap against it to find out"
                )
            return
        except (AttributeError, ValueError, IndexError):
            self.log.error("bad response .. bailing out")
            return
        except socket.error as err:
            self.log.error("socket error: %s" % err)
            return
        if self.BADUSER.startswith(self.AUTHREQ):
            self.log.warning("Bad user = %s - svwar will probably not work!" %
                             self.AUTHREQ)
        # let the fun commence
        self.log.info('Ok SIP device found')
        while 1:
            if self.nomore:
                while 1:
                    try:
                        self.getResponse()
                    except socket.timeout:
                        return
            r, _, _ = select.select(self.rlist, self.wlist, self.xlist,
                                    self.selecttime)
            if r:
                # we got stuff to read off the socket
                self.getResponse()
                self.lastrecvtime = time.time()
            else:
                # check if its been a while since we had a response to prevent
                # flooding - otherwise stop
                timediff = time.time() - self.lastrecvtime
                if timediff > self.maxlastrecvtime:
                    self.nomore = True
                    self.log.warning(
                        'It has been %s seconds since we last received a response - stopping'
                        % timediff)
                    continue
                # no stuff to read .. its our turn to send back something
                try:
                    self.nextuser = next(self.usernamegen)
                except StopIteration:
                    self.nomore = True
                    continue
                except TypeError:
                    self.nomore = True
                    self.log.exception('Bad format string')
                data = self.createRequest(self.method, self.nextuser)
                try:
                    self.log.debug("sending request for %s" % self.nextuser)
                    mysendto(self.sock, data, (self.dsthost, self.dstport))
                    # self.sock.sendto(data,(self.dsthost,self.dstport))
                    if self.sessionpath is not None:
                        if next(self.packetcount):
                            try:
                                if self.guessmode == 1:
                                    pickle.dump(
                                        self.nextuser,
                                        open(
                                            os.path.join(
                                                exportpath,
                                                'lastextension.pkl'), 'wb+'))
                                    self.log.debug('logged last extension %s' %
                                                   self.nextuser)
                                elif self.guessmode == 2:
                                    pickle.dump(
                                        self.guessargs.tell(),
                                        open(
                                            os.path.join(
                                                exportpath,
                                                'lastextension.pkl'), 'wb+'))
                                    self.log.debug('logged last position %s' %
                                                   self.guessargs.tell())
                            except IOError:
                                self.log.warning(
                                    'could not log the last extension scanned')
                except socket.error as err:
                    self.log.error("socket error: %s" % err)
                    break
예제 #13
0
파일: svmap.py 프로젝트: akalex/DevProject
 def start(self):
     from libs.svhelper import makeRequest, createTag
     from libs.svhelper import mysendto
     import socket
     # bind to 5060 - the reason is to maximize compatability with
     # devices that disregard the source port and send replies back
     # to port 5060
     self.log.debug("binding to %s:%s" % (self.bindingip,self.localport))
     while 1:
         # Check if there any ports are available, print error message if not.
         if self.localport > 65535:
             self.log.critical("Could not bind to any port")
             return
         try:
         # Bind the socket to address. The socket must not already be bound.
             self.sock.bind((self.bindingip,self.localport))
             break
         # This exception is raised for socket-related errors. The accompanying value is either a string telling
         # what went wrong or a pair (errno, string) representing an error returned by a system call, similar
         # to the value accompanying os.error.
         except socket.error:
             self.log.debug("could not bind to %s" % self.localport)
             self.localport += 1            
     if self.originallocalport != self.localport:
         self.log.warn("could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead" % (self.bindingip,self.originallocalport, self.localport))
         self.log.info("Make use of the -P option to specify a port to bind to yourself")
     while 1:
         r, w, e = select.select(
             self.rlist,
             self.wlist,
             self.xlist,
             self.selecttime
             )
         if r:
             # we got stuff to read off the socket
             try:
                 buff,srcaddr = self.sock.recvfrom(8192)
                 self.log.debug('got data from %s:%s' % srcaddr)
                 self.log.debug('data: %s' % `buff`)
                 if self.printdebug:
                     print srcaddr
                     print buff
             except socket.error:
                 continue
             self.getResponse(buff,srcaddr)
         else:
             # no stuff to read .. its our turn to send back something
             if self.nomoretoscan:                    
                 try:
                     # having the final sip 
                     self.log.debug("Making sure that no packets get lost")
                     self.log.debug("Come to daddy")
                     while 1:
                         buff,srcaddr = self.sock.recvfrom(8192)
                         if self.printdebug:
                             print srcaddr
                             print buff
                         self.getResponse(buff,srcaddr)
                 except socket.error:
                     break
             try:
                 nextscan = self.scaniter.next()
             except StopIteration:
                 self.log.debug('no more hosts to scan')
                 self.nomoretoscan = True
                 continue
             dstip,dstport,method = nextscan
             self.nextip = dstip
             # Set destination IP and port
             dsthost = (dstip,dstport)
             # Generate new branchunique, by default it not set
             # Returns a python long int with k random bits.
             branchunique = '%s' % random.getrandbits(32)
             localtag = createTag('%s%s' % (''.join(map(lambda x: '%02x' % int(x), dsthost[0].split('.'))),'%04x' % dsthost[1]))
             cseq = 1
             fromaddr = '"%s"<%s>' % (self.fromname,self.fromaddr)
             toaddr = fromaddr
             callid = '%s' % random.getrandbits(80)
             contact = None
             if method != 'REGISTER':
                 contact = 'sip:%s@%s:%s' % (self.extension,self.externalip,self.localport)
             # Make a registration request.
             # More about SIP registration http://tools.ietf.org/search/rfc3261#page-56
             data = makeRequest(
                             method,
                             fromaddr,
                             toaddr,
                             dsthost[0],
                             dsthost[1],
                             callid,
                             self.externalip,
                             branchunique,
                             compact=self.compact,
                             localtag=localtag,
                             contact=contact,
                             accept='application/sdp',
                             localport=self.localport,
                             extension=self.extension
                             )
             try:
                 self.log.debug("sending packet to %s:%s" % dsthost)
                 self.log.debug("packet: %s" % `data`)
                 mysendto(self.sock,data,dsthost)
                 self.sentpackets += 1
                 #self.sock.sendto(data,dsthost)    
                 if self.sessionpath is not None:
                     if self.packetcount.next():
                         try:
                             # Open file for write
                             f=open(os.path.join(self.sessionpath,'lastip.pkl'),'w')
                             # Write a pickled representation of obj to the open file object file.
                             pickle.dump(self.nextip,f)
                             # Close file
                             f.close()
                             self.log.debug('logged last ip %s' % self.nextip)
                         except IOError:
                             self.log.warn('could not log the last ip scanned')
                 if self.first is not None:
                     if self.sentpackets >= self.first:
                         self.log.info('Reached the limit to scan the first %s packets' % self.first)
                         self.nomoretoscan = True
             except socket.error,err:
                 self.log.error( "socket error while sending to %s:%s -> %s" % (dsthost[0],dsthost[1],err))
                 pass
예제 #14
0
 def start(self):
     from libs.svhelper import makeRequest, createTag
     from libs.svhelper import mysendto
     import socket
     # bind to 5060 - the reason is to maximize compatability with
     # devices that disregard the source port and send replies back
     # to port 5060
     self.log.debug("binding to %s:%s" % (self.bindingip,self.localport))
     while 1:
         if self.localport > 65535:
             self.log.critical("Could not bind to any port")
             return
         try:            
             self.sock.bind((self.bindingip,self.localport))
             break
         except socket.error:
             self.log.debug("could not bind to %s" % self.localport)
             self.localport += 1            
     if self.originallocalport != self.localport:
         self.log.warn("could not bind to %s:%s - some process might already be listening on this port. Listening on port %s instead" % (self.bindingip,self.originallocalport, self.localport))
         self.log.info("Make use of the -P option to specify a port to bind to yourself")
     while 1:
         r, w, e = select.select(
             self.rlist,
             self.wlist,
             self.xlist,
             self.selecttime
             )
         if r:
             # we got stuff to read off the socket
             try:
                 buff,srcaddr = self.sock.recvfrom(8192)
                 self.log.debug('got data from %s:%s' % srcaddr)
                 self.log.debug('data: %s' % `buff`)
                 if self.printdebug:
                     print srcaddr
                     print buff
             except socket.error:
                 continue
             self.getResponse(buff,srcaddr)
         else:
             # no stuff to read .. its our turn to send back something
             if self.nomoretoscan:                    
                 try:
                     # having the final sip 
                     self.log.debug("Making sure that no packets get lost")
                     self.log.debug("Come to daddy")
                     while 1:
                         buff,srcaddr = self.sock.recvfrom(8192)
                         if self.printdebug:
                             print srcaddr
                             print buff
                         self.getResponse(buff,srcaddr)
                 except socket.error:
                     break
             try:
                 nextscan = self.scaniter.next()
             except StopIteration:
                 self.log.debug('no more hosts to scan')
                 self.nomoretoscan = True
                 continue
             dstip,dstport,method = nextscan
             self.nextip = dstip
             dsthost = (dstip,dstport)
             branchunique = '%s' % random.getrandbits(32)
             
             localtag = createTag('%s%s' % (''.join(map(lambda x: '%02x' % int(x), dsthost[0].split('.'))),'%04x' % dsthost[1]))
             cseq = 1
             fromaddr = '"%s"<%s>' % (self.fromname,self.fromaddr)
             toaddr = fromaddr
             callid = '%s' % random.getrandbits(80)
             contact = None
             if method != 'REGISTER':
                 contact = 'sip:%s@%s:%s' % (self.extension,self.externalip,self.localport)
             data = makeRequest(
                             method,
                             fromaddr,
                             toaddr,
                             dsthost[0],
                             dsthost[1],
                             callid,
                             self.externalip,
                             branchunique,
                             compact=self.compact,
                             localtag=localtag,
                             contact=contact,
                             accept='application/sdp',
                             localport=self.localport,
                             extension=self.extension
                             )
             try:
                 self.log.debug("sending packet to %s:%s" % dsthost)
                 self.log.debug("packet: %s" % `data`)
                 mysendto(self.sock,data,dsthost)
                 self.sentpackets += 1
                 #self.sock.sendto(data,dsthost)    
                 if self.sessionpath is not None:
                     if self.packetcount.next():
                         try:
                             f=open(os.path.join(self.sessionpath,'lastip.pkl'),'w')
                             pickle.dump(self.nextip,f)
                             f.close()
                             self.log.debug('logged last ip %s' % self.nextip)
                         except IOError:
                             self.log.warn('could not log the last ip scanned')
                 if self.first is not None:
                     if self.sentpackets >= self.first:
                         self.log.info('Reached the limit to scan the first %s packets' % self.first)
                         self.nomoretoscan = True
             except socket.error,err:
                 self.log.error( "socket error while sending to %s:%s -> %s" % (dsthost[0],dsthost[1],err))
                 pass