def to_postdata(self): """Serialize as post data for a POST request.""" logging.info("starting to create post request. param") try: foo = "&".join(["%s=%s" % (escape(str(k)), escape(str(v))) for k, v in self.parameters.iteritems()]) except Exception, e: logging.warn("error from creating post body" + str(e))
def get_signature_base_string(self, method, url, params): """ Builds the signature base string (as defined by OAuth) for this request. Args: method: string The HTTP method used for signing the request. url: string The fully-qualified url of the request. params: string Parameters used to sign the request. Should be a merged set of all querystring, form-urlencoded POST body, and header params. Returns: string A signature base string as defined by the OAuth spec. """ encoded_params = {} for key, value in params.items(): encoded_params[key] = value.encode('utf-8', 'ignore') oauth_request = oauth.OAuthRequest( http_method=method.upper(), http_url=url, parameters=encoded_params) base_str = '&'.join(( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()))) return base_str
def _isValidSignature(self): # Construct a RSA.pubkey object exponent = 65537 public_key_str = """0x\ 00b1e057678343866db89d7dec2518\ 99261bf2f5e0d95f5d868f81d600c9\ a101c9e6da20606290228308551ed3\ acf9921421dcd01ef1de35dd3275cd\ 4983c7be0be325ce8dfc3af6860f7a\ b0bf32742cd9fb2fcd1cd1756bbc40\ 0b743f73acefb45d26694caf4f26b9\ 765b9f65665245524de957e8c547c3\ 58781fdfb68ec056d1""" public_key_long = long(public_key_str, 16) public_key = RSA.construct((public_key_long, exponent)) # Rebuild the message hash locally oauth_request = oauth.OAuthRequest(http_method=self.request.method, http_url=self.request.url, parameters=self.request.params.mixed()) message = '&'.join((oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()),)) local_hash = hashlib.sha1(message).digest() # Apply the public key to the signature from the remote host sig = base64.decodestring(urllib.unquote(self.request.params.mixed()["oauth_signature"])) remote_hash = public_key.encrypt(sig, '')[0][-20:] # Verify that the locally-built value matches the value from the remote server. if local_hash==remote_hash: return True else: return False
def get_signature_base_string(self, method, url, params): """ Builds the signature base string (as defined by OAuth) for this request. Args: method: string The HTTP method used for signing the request. url: string The fully-qualified url of the request. params: string Parameters used to sign the request. Should be a merged set of all querystring, form-urlencoded POST body, and header params. Returns: string A signature base string as defined by the OAuth spec. """ encoded_params = {} for key, value in params.items(): encoded_params[key] = value.encode('utf-8', 'ignore') oauth_request = oauth.OAuthRequest(http_method=method.upper(), http_url=url, parameters=encoded_params) base_str = '&'.join( (oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()))) return base_str
def to_postdata(self): """Serialize as post data for a POST request.""" logging.info('starting to create post request. param') try: foo = '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) \ for k, v in self.parameters.iteritems()]) except Exception, e: logging.warn('error from creating post body' + str(e))
def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = '' raw = '&'.join(sig) return key, raw
def base_string(self): """ Generates the Signature Base String. http://oauth.net/core/1.0/#rfc.section.A.5.1 """ return '&'.join(( escape(self.request.http_method), escape(self.request.url), escape(self.request.normalized_request_params), ))
def request(self, api_url, method="GET", parameters=None, body=None, raw_response=False, converter=gdata.photos.AnyFeedFromString): access_token = self.token if parameters is None: parameters = {'max-results': 10000} http_method = "POST" if method in ["POST", "PUT"] else method oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, token=access_token, http_method=http_method, http_url=api_url, parameters=parameters) oauth_request.sign_request(self.signature_method, self.consumer, access_token) headers = oauth_request.to_header() request_url = oauth_request.to_url() if method == "PUT": headers["X-HTTP-Method-Override"] = "PUT" if body is not None and http_method == "POST": body += "&".join( "%s=%s" % (oauth.escape(str(k)),oauth.escape(str(v))) for k, v in parameters.iteritems()) if http_method == "POST": qs = urlparse.urlparse(oauth_request.to_url()).query qparams = oauth_request._split_url_string(qs) qs = "&".join("%s=%s" % (oauth.escape(str(k)), oauth.escape(str(v))) for k, v in qparams.iteritems()) request_url = oauth_request.get_normalized_http_url() + "?" + qs else: if parameters: request_url = "%s?%s" % (oauth_request.http_url, urllib.urlencode(parameters)) else: request_url = oauth_request.http_url req = urllib2.Request(request_url, data=body, headers=headers) resp = urllib2.urlopen(req) self.last_response = resp resp_content = resp.read() if resp.code > 201: raise Exception('API returned an error', resp_content) #print "%s" % resp_content feed = converter(resp_content) return feed
def base_secrets(self): """ Returns the concatenated encoded values of the Consumer Secret and Token Secret, separated by a ‘&’ character (ASCII code 38), even if either secret is empty. """ key = '' if self.consumer and 'oauth_consumer_secret' in self.consumer: key += escape(self.consumer['oauth_consumer_secret']) key += '&' if self.token and 'oauth_token_secret' in self.token: key += escape(self.token['oauth_token_secret']) return key.encode('ascii')
def prepareRequest(self, postParams): """ The prepareRequest method is used to initialise the request in preparation to sending to twitter. The method returns the url of the resource we are trying to access, and additionally post parameters can be pushed into the postParams argument. """ # get the action and the extra parameters (fnresult, extra_params) = self.getActionAndParams() # if the next page is set, then use that url if self.nextPage is not None: fnresult += self.nextPage # otherwise, build a suitable url else: fnresult += "?rpp=50" if self.highTweetId > 0: fnresult += "&since_id=%s" % (self.highTweetId) # if the language code has been set, then specify the language code also if self.language is not None: fnresult += "&lang=" + self.language # TODO: one day use the map, filter or reduce function once I become enlightened in functional programming for k,v in extra_params.iteritems(): fnresult += "&%s=%s" % (k, oauth.escape(v)) return fnresult
def prepareRequest(self, postParams): """ The prepareRequest method is used to initialise the request in preparation to sending to twitter. The method returns the url of the resource we are trying to access, and additionally post parameters can be pushed into the postParams argument. """ # get the action and the extra parameters (fnresult, extra_params) = self.getActionAndParams() # if the next page is set, then use that url if self.nextPage is not None: fnresult += self.nextPage # otherwise, build a suitable url else: fnresult += "?rpp=50" if self.highTweetId > 0: fnresult += "&since_id=%s" % (self.highTweetId) # if the language code has been set, then specify the language code also if self.language is not None: fnresult += "&lang=" + self.language # TODO: one day use the map, filter or reduce function once I become enlightened in functional programming for k, v in extra_params.iteritems(): fnresult += "&%s=%s" % (k, oauth.escape(v)) return fnresult
def base_secrets(self): """ Returns the concatenated encoded values of the Consumer Secret and Token Secret, separated by a ‘&’ character (ASCII code 38), even if either secret is empty. """ key = '' if self.consumer and 'oauth_token_secret' in self.consumer: key += escape(self.consumer['oauth_token_secret']) key += '&' if self.token and 'oauth_token_secret' in self.token: key += escape(self.token['oauth_token_secret']) return key
def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" auth_header = 'OAuth realm="%s"' % realm # Add the oauth parameters. if self.parameters: for k, v in self.parameters.iteritems(): auth_header += ', %s="%s"' % (k, escape(str(v))) return {'Authorization': auth_header}
def to_header(self, realm=""): """Serialize as a header for an HTTPAuth request.""" auth_header = 'OAuth realm="%s"' % realm # Add the oauth parameters. if self.parameters: for k, v in self.parameters.iteritems(): auth_header += ', %s="%s"' % (k, escape(str(v))) return {"Authorization": auth_header}
def request_to_header(request, realm=''): """Serialize as a header for an HTTPAuth request.""" auth_header = 'OAuth realm="%s"' % realm # Add the oauth parameters. if request.parameters: for k, v in request.parameters.iteritems(): if k.startswith('oauth_') or k.startswith('x_auth_'): auth_header += ', %s="%s"' % (k, oauth.escape(str(v))) return {'Authorization': auth_header}
def _isValidSignature(self): # Code lab hack: # If the container is 'appengine' (e.g. app is running on localhost), return True if self.request.get('oauth_consumer_key') == 'appengine': return True # Construct a RSA.pubkey object exponent = 65537 public_key_str = """0x\ 00b1e057678343866db89d7dec2518\ 99261bf2f5e0d95f5d868f81d600c9\ a101c9e6da20606290228308551ed3\ acf9921421dcd01ef1de35dd3275cd\ 4983c7be0be325ce8dfc3af6860f7a\ b0bf32742cd9fb2fcd1cd1756bbc40\ 0b743f73acefb45d26694caf4f26b9\ 765b9f65665245524de957e8c547c3\ 58781fdfb68ec056d1""" public_key_long = long(public_key_str, 16) public_key = RSA.construct((public_key_long, exponent)) # Rebuild the message hash locally oauth_request = oauth.OAuthRequest(http_method=self.request.method, http_url=self.request.url, parameters=self.request.params.mixed()) message = '&'.join(( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), )) local_hash = hashlib.sha1(message).digest() # Apply the public key to the signature from the remote host sig = base64.decodestring( urllib.unquote(self.request.params.mixed()["oauth_signature"])) remote_hash = public_key.encrypt(sig, '')[0][-20:] # Verify that the locally-built value matches the value from the remote server. if local_hash == remote_hash: return True else: return False
def request_to_header(self,request, realm=''): '''Serialize as a header for an HTTPAuth request.''' logging.info('Building Request Header...') auth_header = 'OAuth realm=\'%s\'' % realm if request.parameters: for k, v in request.parameters.iteritems(): if k.startswith('oauth_') or k.startswith('x_auth_'): auth_header += ', %s="%s"' % (k, oauth.escape(str(v))) logging.info('Header ready....') return {'Authorization': auth_header}
def __init__(self, key): """ Creates a validator based off of the HMAC-SHA1 signing mechanism. Args: key: string The shared secret key used to sign this request. Typically, this value will be shared with the owner of an application at the time the application is registered with the container. exponent: int The RSA public key exponent. """ self.hmac_key = '%s&' % oauth.escape(key)
def update_all_distributed(request): """ """ logging.debug("Getting data.") params = { "callback": request.build_absolute_uri(reverse("update_all_distributed_callback")), "user_id": request.session["facility_user"].id, } query_string = "&".join(["%s=%s" % (k,oauth.escape(v)) for k,v in params.items()]) central_url = CENTRAL_SERVER_URL + reverse("update_all_central") + "?" + query_string return HttpResponseRedirect(central_url)
def request(self, api_url, method="GET", parameters=None, body=None, raw_response=False, gdata_service=None, converter=None): access_token = self.token http_method = "POST" if method in ["POST", "PUT"] else method oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, token=access_token, http_method=http_method, http_url=api_url, parameters=parameters) oauth_request.sign_request(self.signature_method, self.consumer, access_token) headers = oauth_request.to_header() request_url = oauth_request.to_url() if method == "PUT": headers["X-HTTP-Method-Override"] = "PUT" if body is not None and http_method == "POST": body += "&".join( "%s=%s" % (oauth.escape(str(k)),oauth.escape(str(v))) for k, v in parameters.iteritems()) if http_method == "POST": qs = urlparse.urlparse(oauth_request.to_url()).query qparams = oauth_request._split_url_string(qs) qs = "&".join("%s=%s" % (oauth.escape(str(k)), oauth.escape(str(v))) for k, v in qparams.iteritems()) request_url = oauth_request.get_normalized_http_url() + "?" + qs else: if parameters: request_url = "%s?%s" % (oauth_request.http_url, urllib.urlencode(parameters)) else: request_url = oauth_request.http_url resp = gdata_service.GetFeed(request_url, extra_headers=headers, converter=converter) return resp
def request(self, api_url, method="GET", parameters=None, body=None, raw_response=False): access_token = self.token http_method = "POST" if method in ["POST", "PUT"] else method oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, token=access_token, http_method=http_method, http_url=api_url, parameters=parameters) oauth_request.sign_request(self.signature_method, self.consumer, access_token) headers = {} if method == "PUT": headers["X-HTTP-Method-Override"] = "PUT" if body is not None and http_method == "POST": body += "&".join( "%s=%s" % (oauth.escape(str(k)),oauth.escape(str(v))) for k, v in parameters.iteritems()) request_url = oauth_request.to_url() if http_method == "POST": qs = urlparse.urlparse(oauth_request.to_url()).query qparams = oauth_request._split_url_string(qs) qs = "&".join("%s=%s" % (oauth.escape(str(k)), oauth.escape(str(v))) for k, v in qparams.iteritems()) request_url = oauth_request.get_normalized_http_url() + "?" + qs #resp = urlfetch.fetch(request_url, payload=body, headers=headers, method=http_method) req = urllib2.Request(request_url, data=body, headers=headers) resp = urllib2.urlopen(req) self.last_response = resp resp_content = resp.read() if resp.code > 201: raise Exception("API returned an error", resp_content) api_response = resp_content if raw_response else simplejson.loads(resp_content) return api_response
def update_all_distributed(request): """ """ logging.debug("Getting data.") params = { "callback": request.build_absolute_uri(reverse("update_all_distributed_callback")), "user_id": request.session["facility_user"].id, } query_string = "&".join( ["%s=%s" % (k, oauth.escape(v)) for k, v in params.items()]) central_url = CENTRAL_SERVER_URL + reverse( "update_all_central") + "?" + query_string return HttpResponseRedirect(central_url)
def test_escape(self): string = 'http://whatever.com/~someuser/?test=test&other=other' self.assert_('~' in oauth.escape(string)) string = '../../../../../../../etc/passwd' self.assert_('../' not in oauth.escape(string))