Пример #1
0
    def start(self):        
        import socket, pickle
        from helper 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
Пример #2
0
    def start(self):        
        import socket, pickle
        from helper 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 helper import ,getCredentials,getRealm,getCID
        import socket, pickle
        from helper 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.dsthost)
        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):
        #from helper import ,getCredentials,getRealm,getCID
        import socket, pickle
        from helper 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.dsthost)
        try:
            mysendto(self.sock,data,(self.dsthost,self.dstport))
        except socket.error,err:
            self.log.error("socket error: %s" % err)
            return
Пример #5
0
    def getResponse(self):
        from helper import getNonce,getCredentials,getRealm,getCID,getTag        
        from base64 import b64decode
        from helper import parseHeader
        from helper import mysendto
        import re
        # we got stuff to read off the socket
        from socket import error as socketerror
        buff,srcaddr = self.sock.recvfrom(8192)
        try:
            extension = getTag(buff)
        except TypeError:
            
            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

        # send an ack to any responses which match
        _tmp = parseHeader(buff)
        if _tmp['code'] >= 200:
            self.log.debug('will try to send an ACK response')
            if _tmp['code'] >= 300:
                # handle differently
                pass
            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
            username = _tmp['headers']['from'][0].split('"')[1]
            cseq = _tmp['headers']['cseq'][0]
            cid = _tmp['headers']['call-id'][0]
            ackreq = self.createRequest('ACK',
                                   username=username,
                                   cid=cid,
                                   cseq=cseq,
                                   )
            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 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:
                sys.exit(1)
                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)
        
        # 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
Пример #6
0
     # we got stuff to read off the socket
     self.getResponse()
 else:
     # 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(self.guessargs.tell(),open(os.path.join(exportpath,'lastextension.pkl'),'w'))
                         self.log.debug('logged last position %s' % self.guessargs.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
Пример #7
0
    def getResponse(self):
        from helper import getNonce,getCredentials,getRealm,getCID,getTag        
        from base64 import b64decode
        from helper import parseHeader
        from helper import mysendto
        import re
        # we got stuff to read off the socket
        from socket import error as socketerror
        buff,srcaddr = self.sock.recvfrom(8192)
        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 not self.disableack:
            # send an ack to any responses which match
            _tmp = parseHeader(buff)
            if 300 > _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]
                cid = _tmp['headers']['call-id'][0]
                ackreq = self.createRequest('ACK',
                                       username=username,
                                       cid=cid,
                                       cseq=cseq,
                                       )
                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 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
Пример #8
0
     self.nomore = True
     self.log.warn('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(self.guessargs.tell(),open(os.path.join(exportpath,'lastextension.pkl'),'w'))
                     self.log.debug('logged last position %s' % self.guessargs.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 helper import makeRequest, createTag
     from helper 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