Beispiel #1
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
 def start(self):
     # bind to 5060 - the reason is to maximize compatability with
     # devices that disregard the source port and send replies back
     # to port 5060
     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")
     while 1:
         r, _, _ = 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)
                 host, port, *_ = srcaddr
                 self.log.debug('got data from %s:%s' % (str(host), str(port)))
                 self.log.debug('data: %s' % buff.__repr__())
                 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 = next(self.scaniter)
             except StopIteration:
                 self.log.debug('no more hosts to scan')
                 self.nomoretoscan = True
                 continue
             dstip,dstport,method = nextscan
             self.nextip = dstip
             dsthost = (dstip,dstport)
             domain = dsthost[0]
             branchunique = '%s' % random.getrandbits(32)
             if self.ipv6 and check_ipv6(dsthost[0]):
                 domain = '[' + dsthost[0] + ']'
                 localtag = createTag('%s%s' % (''.join(map(lambda x:
                     '%s' % x, dsthost[0].split(':'))), '%04x' % dsthost[1]))
             else:
                 localtag = createTag('%s%s' % (''.join(map(lambda x:
                     '%02x' % int(x), dsthost[0].split('.'))),'%04x' % dsthost[1]))
             if self.ipv6:
                 fromaddr = '"%s"<sip:100@%s>' % (self.fromname, domain)
             else:
                 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,
                             domain,
                             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.__repr__())
                 mysendto(self.sock,data,dsthost)
                 self.sentpackets += 1
                 #self.sock.sendto(data,dsthost)
                 if self.sessionpath is not None:
                     if next(self.packetcount):
                         try:
                             f=open(os.path.join(self.sessionpath,'lastip.pkl'),'wb+')
                             pickle.dump(self.nextip,f)
                             f.close()
                             self.log.debug('logged last ip %s' % self.nextip)
                         except IOError:
                             self.log.warning('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 as err:
                 self.log.error( "socket error while sending to %s:%s -> %s" % (dsthost[0],dsthost[1],err))
                 pass
Beispiel #3
0
    def getResponse(self):
        # we got stuff to read off the socket
        buff, srcaddr = self.sock.recvfrom(8192)
        if self.printdebug:
            print(srcaddr)
            print(buff)
        buff = buff.decode('utf-8')
        try:
            extension = getTag(buff).decode('utf-8', 'ignore')
        except (TypeError, AttributeError):
            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 'code' in _tmp):
                return
            if 699 > _tmp['code'] >= 200:
                self.log.debug('will try to send an ACK response')
                if 'headers' not in _tmp:
                    self.log.debug('no headers?')
                    return
                if 'from' not in _tmp['headers']:
                    self.log.debug('no from?')
                    return
                if 'cseq' not in _tmp['headers']:
                    self.log.debug('no cseq')
                    return
                if 'call-id' not in _tmp['headers']:
                    self.log.debug('no caller id')
                    return
                try:
                    # _tmp['headers']['from'][0].split('"')[1]
                    username = getTag(buff)
                except IndexError:
                    self.log.warning('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.warning(
                    "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.warning("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.warning("We got an unknown response")
            self.log.error("Response: %s" % buff.__repr__())
            self.log.debug("1st line: %s" % firstline.__repr__())
            self.log.debug("Bad user: %s" % self.BADUSER.__repr__())
            self.nomore = True
Beispiel #4
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 ..
        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 1:
            r, _, _ = 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.warning("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.warning(
                        '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.auth['qop'], self.auth[
                            'algorithm'], self.auth['opaque'] = 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'])
                        if self.auth['algorithm'] == "md5-sess" or self.auth['qop'] == "auth":
                            self.auth["noncecount"] = self.noncecount
                            self.noncecount += 1

                    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(self.sessionpath, 'lastpasswd.pkl'), 'wb+'))
                                    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'), 'wb+'))
                                    self.log.debug(
                                        'logged last position %s' % self.crackargs.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