Python urllib2.HTTPDigestAuthHandler() Examples

The following are 21 code examples for showing how to use urllib2.HTTPDigestAuthHandler(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module urllib2 , or try the search function .

Example 1
Project: ccs-calendarserver   Author: apple   File: population.py    License: Apache License 2.0 6 votes vote down vote up
def _createUser(self, number):
        record = self._records[number]
        user = record.uid
        authBasic = HTTPBasicAuthHandler(password_mgr=HTTPPasswordMgrWithDefaultRealm())
        authBasic.add_password(
            realm=None,
            uri=self.servers[record.podID]["uri"],
            user=user.encode('utf-8'),
            passwd=record.password.encode('utf-8'))
        authDigest = HTTPDigestAuthHandler(passwd=HTTPPasswordMgrWithDefaultRealm())
        authDigest.add_password(
            realm=None,
            uri=self.servers[record.podID]["uri"],
            user=user.encode('utf-8'),
            passwd=record.password.encode('utf-8'))
        return record, user, {"basic": authBasic, "digest": authDigest, } 
Example 2
Project: ccs-calendarserver   Author: apple   File: ical.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    from urllib2 import HTTPDigestAuthHandler
    from twisted.internet import reactor
    auth = HTTPDigestAuthHandler()
    auth.add_password(
        realm="Test Realm",
        uri="http://127.0.0.1:8008/",
        user="user01",
        passwd="user01")

    addObserver(RequestLogger().observe)

    from sim import _DirectoryRecord
    client = OS_X_10_6(
        reactor, 'http://127.0.0.1:8008/',
        _DirectoryRecord(
            u'user01', u'user01', u'User 01', u'user01@example.org'),
        auth)
    d = client.run()
    d.addErrback(err, "10.6 client run() problem")
    d.addCallback(lambda ignored: reactor.stop())
    reactor.run() 
Example 3
Project: ccs-calendarserver   Author: apple   File: report_principals.py    License: Apache License 2.0 6 votes vote down vote up
def measure(host, port, dtrace, attendeeCount, samples):
    user = password = "user01"
    root = "/"
    principal = "/"
    calendar = "report-principal"

    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri="http://%s:%d/" % (host, port),
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # Set up the calendar first
    yield initialize(agent, host, port, user, password, root, principal, calendar)

    url = 'http://%s:%d/principals/' % (host, port)
    headers = Headers({"content-type": ["text/xml"]})

    samples = yield sample(
        dtrace, samples, agent,
        lambda: ('REPORT', url, headers, StringProducer(body)))
    returnValue(samples) 
Example 4
Project: peach   Author: MozillaSecurity   File: http.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def send(self, data):
        """
        Send data via sendall.

        @type	data: string
        @param	data: Data to send
        """

        passmgr = urllib2.HTTPPasswordMgr()
        passmgr.add_password(self._realm, self._url, self._username, self._password)

        auth_handler = urllib2.HTTPDigestAuthHandler(passmgr)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)

        req = urllib2.Request(self._url, data, self._headers)

        try:
            self._fd = urllib2.urlopen(req)
        except:
            self._fd = None 
Example 5
Project: python-mysql-pool   Author: LuciferJack   File: connection.py    License: MIT License 5 votes vote down vote up
def __init__(self, username, password,  # pylint: disable=E1002
                 verbose=0, use_datetime=False, https_handler=None):
        """Initialize"""
        if PY2:
            Transport.__init__(self, use_datetime=False)
        else:
            super().__init__(use_datetime=False)
        self._username = username
        self._password = password
        self._use_datetime = use_datetime
        self.verbose = verbose
        self._username = username
        self._password = password

        self._handlers = []

        if self._username and self._password:
            self._passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
            self._auth_handler = urllib2.HTTPDigestAuthHandler(self._passmgr)
        else:
            self._auth_handler = None
            self._passmgr = None

        if https_handler:
            self._handlers.append(https_handler)
            self._scheme = 'https'
        else:
            self._scheme = 'http'

        if self._auth_handler:
            self._handlers.append(self._auth_handler) 
Example 6
Project: ccs-calendarserver   Author: apple   File: _event_create.py    License: Apache License 2.0 5 votes vote down vote up
def measure(calendar, organizerSequence, events, host, port, dtrace, samples):
    """
    Benchmark event creation.
    """
    user = password = "user%02d" % (organizerSequence,)
    root = "/"
    principal = "/"

    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri="http://%s:%d/" % (host, port),
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # First set things up
    yield initialize(agent, host, port, user, password, root, principal, calendar)

    method = 'PUT'
    uri = 'http://%s:%d/calendars/__uids__/%s/%s/foo-%%d.ics' % (
        host, port, user, calendar)
    headers = Headers({"content-type": ["text/calendar"]})

    # Sample it a bunch of times
    samples = yield sample(
        dtrace, samples,
        agent, ((method, uri % (i,), headers, StringProducer(body))
                for (i, body)
                in events).next,
        CREATED)
    returnValue(samples) 
Example 7
Project: ccs-calendarserver   Author: apple   File: find_events.py    License: Apache License 2.0 5 votes vote down vote up
def measure(host, port, dtrace, numEvents, samples):
    user = password = "user11"
    root = "/"
    principal = "/"

    uri = "http://%s:%d/" % (host, port)
    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri=uri,
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # Create the number of calendars necessary
    account = CalDAVAccount(
        agent,
        "%s:%d" % (host, port),
        user=user, password=password,
        root=root, principal=principal)
    cal = "calendars/users/%s/find-events/" % (user,)
    yield account.makeCalendar("/" + cal)

    # Create the indicated number of events on the calendar
    yield uploadEvents(numEvents, agent, uri, cal)

    body = StringProducer(PROPFIND)
    params = (
        ('PROPFIND',
         '%scalendars/__uids__/%s/find-events/' % (uri, user),
         Headers({"depth": ["1"], "content-type": ["text/xml"]}), body)
        for i in count(1))

    samples = yield sample(dtrace, samples, agent, params.next, MULTI_STATUS)

    # Delete the calendar we created to leave the server in roughly
    # the same state as we found it.
    yield account.deleteResource("/" + cal)

    returnValue(samples) 
Example 8
Project: ccs-calendarserver   Author: apple   File: find_calendars.py    License: Apache License 2.0 5 votes vote down vote up
def measure(host, port, dtrace, numCalendars, samples):
    # There's already the "calendar" calendar
    numCalendars -= 1

    user = password = "user10"
    root = "/"
    principal = "/"

    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri="http://%s:%d/" % (host, port),
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # Create the number of calendars necessary
    account = CalDAVAccount(
        agent,
        "%s:%d" % (host, port),
        user=user, password=password,
        root=root, principal=principal)
    cal = "/calendars/users/%s/propfind-%%d/" % (user,)
    for i in range(numCalendars):
        yield account.makeCalendar(cal % (i,))

    body = StringProducer(PROPFIND)
    params = (
        ('PROPFIND', 'http://%s:%d/calendars/__uids__/%s/' % (host, port, user),
         Headers({"depth": ["1"], "content-type": ["text/xml"]}), body)
        for i in count(1))

    samples = yield sample(dtrace, samples, agent, params.next, MULTI_STATUS)

    # Delete the calendars we created to leave the server in roughly
    # the same state as we found it.
    for i in range(numCalendars):
        yield account.deleteResource(cal % (i,))

    returnValue(samples) 
Example 9
Project: peach   Author: MozillaSecurity   File: http.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def send(self, data):

        passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passmgr.add_password(None, self._authurl, self._username, self._password)

        auth_handler = urllib2.HTTPDigestAuthHandler(passmgr)
        opener = urllib2.build_opener(auth_handler)
        urllib2.install_opener(opener)

        req = urllib2.Request(self._url, data, self._headers)

        try:
            self._fd = urllib2.urlopen(req)
        except:
            self._fd = None 
Example 10
Project: ironpython2   Author: IronLanguages   File: test_urllib2.py    License: Apache License 2.0 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 11
Project: BinderFilter   Author: dxwu   File: test_urllib2.py    License: MIT License 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 12
Project: oss-ftp   Author: aliyun   File: test_urllib2.py    License: MIT License 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 13
Project: ccs-calendarserver   Author: apple   File: diagnose.py    License: Apache License 2.0 4 votes vote down vote up
def connectToAgent(password):

    print()
    print("Agent:")

    url = "http://localhost:62308/gateway/"
    user = "com.apple.calendarserver"
    auth_handler = urllib2.HTTPDigestAuthHandler()
    auth_handler.add_password(
        realm="/Local/Default",
        uri=url,
        user=user,
        passwd=password
    )
    opener = urllib2.build_opener(auth_handler)
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)

    # Send HTTP POST request
    request = urllib2.Request(url, readCommand)
    try:
        print("Attempting to send a request to the agent...")
        response = urllib2.urlopen(request, timeout=30)
    except Exception as e:
        print("Can't connect to agent: {}".format(e))
        return False

    html = response.read()
    code = response.getcode()
    if code == 200:
        try:
            data = readPlistFromString(html)
        except Exception as e:
            print(
                "Could not parse response from agent: {error}\n{html}".format(
                    error=e, html=html
                )
            )
            return False

        if "result" in data:
            print("...success")
        else:
            print("Error in agent's response:\n{}".format(html))
            return False
    else:
        print("Got an error back from the agent: {code} {html}".format(
            code=code, html=html)
        )

    return True 
Example 14
Project: ccs-calendarserver   Author: apple   File: event_move.py    License: Apache License 2.0 4 votes vote down vote up
def measure(host, port, dtrace, attendeeCount, samples):
    organizerSequence = 1
    user = password = "user%02d" % (organizerSequence,)
    root = "/"
    principal = "/"

    # Two calendars between which to move the event.
    fooCalendar = "event-move-foo-benchmark"
    barCalendar = "event-move-bar-benchmark"

    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri="http://%s:%d/" % (host, port),
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # Set up the calendars first
    for calendar in [fooCalendar, barCalendar]:
        yield initialize(
            agent, host, port, user, password, root, principal, calendar)

    fooURI = 'http://%s:%d/calendars/__uids__/%s/%s/some-event.ics' % (
        host, port, user, fooCalendar)
    barURI = 'http://%s:%d/calendars/__uids__/%s/%s/some-event.ics' % (
        host, port, user, barCalendar)

    # Create the event that will move around
    headers = Headers({"content-type": ["text/calendar"]})
    yield agent.request(
        'PUT', fooURI, headers,
        StringProducer(makeEvent(1, organizerSequence, attendeeCount)))

    # Move it around sooo much
    source = cycle([fooURI, barURI])
    dest = cycle([barURI, fooURI])

    params = (
        ('MOVE', source.next(),
         Headers({"destination": [dest.next()], "overwrite": ["F"]}))
        for i in count(1))

    samples = yield sample(dtrace, samples, agent, params.next, CREATED)
    returnValue(samples) 
Example 15
Project: ccs-calendarserver   Author: apple   File: vfreebusy_vary_attendees.py    License: Apache License 2.0 4 votes vote down vote up
def measure(host, port, dtrace, attendees, samples):
    userNumber = 1
    user = password = "user%02d" % (userNumber,)
    root = "/"
    principal = "/"
    calendar = "vfreebusy-vary-attendees-benchmark"

    targets = range(2, attendees + 2)

    authinfo = HTTPDigestAuthHandler()

    # Set up authentication info for our own user and all the other users that
    # may need an event created on one of their calendars.
    for i in [userNumber] + targets:
        targetUser = "user%02d" % (i,)
        for path in ["calendars/users/%s/" % (targetUser,),
                     "calendars/__uids__/10000000-0000-0000-0000-000000000%03d/" % (i,)]:
            authinfo.add_password(
                realm="Test Realm",
                uri="http://%s:%d/%s" % (host, port, path),
                user=targetUser, passwd=targetUser)

    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # Set up events on about half of the target accounts
    baseTime = datetime.now().replace(minute=45, second=0, microsecond=0)
    for i in targets[::2]:
        targetUser = "user%02d" % (i,)
        account = CalDAVAccount(
            agent,
            "%s:%d" % (host, port),
            user=targetUser, password=password,
            root=root, principal=principal)
        cal = "/calendars/users/%s/%s/" % (targetUser, calendar)
        yield account.deleteResource(cal)
        yield account.makeCalendar(cal)
        yield account.writeData(cal + "foo.ics", makeEventNear(baseTime, i), "text/calendar")

    # And now issue the actual VFREEBUSY request
    method = 'POST'
    uri = 'http://%s:%d/calendars/__uids__/10000000-0000-0000-0000-000000000001/outbox/' % (host, port)
    headers = Headers({
        "content-type": ["text/calendar"],
        "originator": ["mailto:%s@example.com" % (user,)],
        "recipient": [", ".join(["urn:x-uid:10000000-0000-0000-0000-000000000%03d" % (i,) for i in [userNumber] + targets])]})
    body = StringProducer(VFREEBUSY % {
        "attendees": "".join([
            "ATTENDEE:urn:x-uid:10000000-0000-0000-0000-000000000%03d\n" % (i,)
            for i in [userNumber] + targets]),
        "start": formatDate(baseTime.replace(hour=0, minute=0)) + 'Z',
        "end": formatDate(
            baseTime.replace(hour=0, minute=0) + timedelta(days=1)) + 'Z'})

    samples = yield sample(
        dtrace, samples,
        agent, lambda: (method, uri, headers, body),
        OK)

    returnValue(samples) 
Example 16
Project: ccs-calendarserver   Author: apple   File: vfreebusy.py    License: Apache License 2.0 4 votes vote down vote up
def measure(host, port, dtrace, events, samples):
    user = password = "user01"
    uid = "10000000-0000-0000-0000-000000000001"
    root = "/"
    principal = "/"
    calendar = "vfreebusy-benchmark"

    authinfo = HTTPDigestAuthHandler()
    authinfo.add_password(
        realm="Test Realm",
        uri="http://%s:%d/" % (host, port),
        user=user,
        passwd=password)
    agent = AuthHandlerAgent(Agent(reactor), authinfo)

    # First set things up
    account = yield initialize(
        agent, host, port, user, password, root, principal, calendar)

    base = "/calendars/users/%s/%s/foo-%%d.ics" % (user, calendar)
    baseTime = datetime.now().replace(hour=12, minute=15, second=0, microsecond=0)
    for i, cal in enumerate(makeEvents(baseTime, events)):
        yield account.writeData(base % (i,), cal, "text/calendar")

    method = 'POST'
    uri = 'http://%s:%d/calendars/__uids__/%s/outbox/' % (host, port, user)
    headers = Headers({
        "content-type": ["text/calendar"],
        "originator": ["mailto:%s@example.com" % (user,)],
        "recipient": ["urn:x-uid:%s, urn:x-uid:10000000-0000-0000-0000-000000000002" % (uid,)]})

    vfb = VFREEBUSY % {
        "attendees": "".join([
            "ATTENDEE:urn:x-uid:%s\n" % (uid,),
            "ATTENDEE:urn:x-uid:10000000-0000-0000-0000-000000000002\n"]),
        "start": formatDate(baseTime.replace(hour=0, minute=0)) + 'Z',
        "end": formatDate(
            baseTime.replace(hour=0, minute=0) + timedelta(days=1)) + 'Z'}
    body = StringProducer(vfb.replace("\n", "\r\n"))

    samples = yield sample(
        dtrace, samples,
        agent, lambda: (method, uri, headers, body),
        OK)
    returnValue(samples) 
Example 17
Project: gcblue   Author: gcblue   File: test_urllib2.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 18
Project: medicare-demo   Author: ofermend   File: test_urllib2.py    License: Apache License 2.0 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 19
Project: darkc0de-old-stuff   Author: tuwid   File: option.py    License: GNU General Public License v3.0 4 votes vote down vote up
def __setHTTPAuthentication():
    """
    Check and set the HTTP authentication method (Basic or Digest),
    username and password to perform HTTP requests with.
    """

    global authHandler

    if not conf.aType and not conf.aCred:
        return

    elif conf.aType and not conf.aCred:
        errMsg  = "you specified the HTTP Authentication type, but "
        errMsg += "did not provide the credentials"
        raise sqlmapSyntaxException, errMsg

    elif not conf.aType and conf.aCred:
        errMsg  = "you specified the HTTP Authentication credentials, "
        errMsg += "but did not provide the type"
        raise sqlmapSyntaxException, errMsg

    parseTargetUrl()

    debugMsg = "setting the HTTP Authentication type and credentials"
    logger.debug(debugMsg)

    aTypeLower = conf.aType.lower()

    if aTypeLower not in ( "basic", "digest" ):
        errMsg  = "HTTP Authentication type value must be "
        errMsg += "Basic or Digest"
        raise sqlmapSyntaxException, errMsg

    aCredRegExp = re.search("^(.*?)\:(.*?)$", conf.aCred)

    if not aCredRegExp:
        errMsg  = "HTTP Authentication credentials value must be "
        errMsg += "in format username:password"
        raise sqlmapSyntaxException, errMsg

    authUsername = aCredRegExp.group(1)
    authPassword = aCredRegExp.group(2)

    passwordMgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passwordMgr.add_password(None, "%s://%s" % (conf.scheme, conf.hostname), authUsername, authPassword)

    if aTypeLower == "basic":
        authHandler = urllib2.HTTPBasicAuthHandler(passwordMgr)
    elif aTypeLower == "digest":
        authHandler = urllib2.HTTPDigestAuthHandler(passwordMgr) 
Example 20
Project: CTFCrackTools-V2   Author: Acmesec   File: test_urllib2.py    License: GNU General Public License v3.0 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2) 
Example 21
Project: CTFCrackTools   Author: Acmesec   File: test_urllib2.py    License: GNU General Public License v3.0 4 votes vote down vote up
def test_basic_and_digest_auth_handlers(self):
        # HTTPDigestAuthHandler raised an exception if it couldn't handle a 40*
        # response (http://python.org/sf/1479302), where it should instead
        # return None to allow another handler (especially
        # HTTPBasicAuthHandler) to handle the response.

        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
        # try digest first (since it's the strongest auth scheme), so we record
        # order of calls here to check digest comes first:
        class RecordingOpenerDirector(OpenerDirector):
            def __init__(self):
                OpenerDirector.__init__(self)
                self.recorded = []
            def record(self, info):
                self.recorded.append(info)
        class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("digest")
                urllib2.HTTPDigestAuthHandler.http_error_401(self,
                                                             *args, **kwds)
        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
            def http_error_401(self, *args, **kwds):
                self.parent.record("basic")
                urllib2.HTTPBasicAuthHandler.http_error_401(self,
                                                            *args, **kwds)

        opener = RecordingOpenerDirector()
        password_manager = MockPasswordManager()
        digest_handler = TestDigestAuthHandler(password_manager)
        basic_handler = TestBasicAuthHandler(password_manager)
        realm = "ACME Networks"
        http_handler = MockHTTPHandler(
            401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
        opener.add_handler(basic_handler)
        opener.add_handler(digest_handler)
        opener.add_handler(http_handler)

        # check basic auth isn't blocked by digest handler failing
        self._test_basic_auth(opener, basic_handler, "Authorization",
                              realm, http_handler, password_manager,
                              "http://acme.example.com/protected",
                              "http://acme.example.com/protected",
                              )
        # check digest was tried before basic (twice, because
        # _test_basic_auth called .open() twice)
        self.assertEqual(opener.recorded, ["digest", "basic"]*2)