How to switch off logout encryption in simplesamlphp - encryption

All my logout responses from simplesamlphp IdP come encrypted. I looked in simplesamlphp docs but cannot find any option to switch off encryption.
(I have logout signing on; but signing should be independent of encryption, and use Redirect binding)
Is it possible to send logout responses via Redirect binding inencrypted? Or is always on by default for some reason?

Paramenter 'assertion.encryption' defined on IdP remote metadata
Whether assertions received from this IdP must be encrypted. The default value is FALSE. If this option is set to TRUE, assertions from the IdP must be encrypted. Unencrypted assertions will be rejected.
Note that this option overrides the option with the same name in the SP configuration.
Reference: http://simplesamlphp.org/docs/stable/simplesamlphp-reference-idp-remote
Parameter 'assertion.encryption' in saml20-idp-hosted.php
Whether assertions sent from this IdP should be encrypted. The default value is FALSE.
Note that this option can be set for each SP in the SP-remote metadata.
Reference: http://simplesamlphp.org/docs/stable/simplesamlphp-reference-idp-hosted
Edited to add an explanation:
simpleSAMLphp uses the function encryptAssertion (modules/saml/lib/IdP/SAML2.php) to decide if encrypt or not all the assertions that it handler. This function checks the values of the 'assertion.encryption' defined on the IdP/SP metadata file (if this parameter is not defined the assertion is not encrypted
private static function encryptAssertion(SimpleSAML_Configuration $idpMetadata,
SimpleSAML_Configuration $spMetadata, SAML2_Assertion $assertion) {
$encryptAssertion = $spMetadata->getBoolean('assertion.encryption', NULL);
if ($encryptAssertion === NULL) {
$encryptAssertion = $idpMetadata->getBoolean('assertion.encryption', FALSE);
}
if (!$encryptAssertion) {
/* We are _not_ encrypting this assertion, and are therefore done. */
return $assertion;
}

The issue was with something else. I just reused the code that processed POST binding to also process Redirect binding; but with Redirect binding, the payload is deflated, so the code for POST cannot be reused directly.

Related

Browser not saving cookie sent by Golang backend

I know this question has been asked a bunch of times, but I tried most of the answers and still can't get it to work.
I have a Golang API with net/http package and a JS frontend. I have a function
func SetCookie(w *http.ResponseWriter, email string) string {
val := uuid.NewString()
http.SetCookie(*w, &http.Cookie{
Name: "goCookie",
Value: val,
Path: "/",
})
return val
}
This function is called when the user logs in, and I expect it to be sent to all the other endpoints. This works as expected with Postman. However, when it comes to the browser, I can't seem to get it to remember the cookie or even send it to other endpoints.
An example of JS using an endpoint
async function getDataWithQuery(query, schema){
let raw = `{"query":"${query}", "schema":"${schema}"}`;
let requestOptions = {
method: 'POST',
body: raw,
redirect: 'follow',
};
try{
let dataJson = await fetch("http://localhost:8080/query/", requestOptions)
data = await dataJson.json();
}catch(error){
console.log(error);
}
return data;
}
I tried answers like setting SameSite attribute in Golang, or using credential: "include" in JS with no luck.
Thanks to the discussion in the comments, I found some hints about the problem.
Saving cookies (both API and frontend on the same host)
I used document.cookie to save the cookie. I set the options by hand since calling res.cookie on the response of the API fetch only returned the value. An example is document.cookie = `goCookie=${res.cookie}; path=/; domain=localhost;.
Sending cookies
This has been answered before in previous questions and answered again in the comments. The problem was that I used credential:'include' instead of the correct credentials:'include' (plural).
CORS and cookies
In case the API and the frontend are not on the same host you will have to modify both the API and the frontend.
frontend
The cookie has to have the domain of the API since it's the API that requires it, not the frontend. So, for security reasons, you can't set a cookie for a domain (API) from another domain (frontend). A solution would be redirect the user to an API endpoint that returns Set-Cookie header in the response header. This solution signals the browser to register that cookie with the domain attached to it (the API's domain, since the API sent it).
Also, you still need to include credentials:'include' in the frontend.
API
You will need to set a few headers. The ones I set are
w.Header().Set("Access-Control-Allow-Origin", frontendOrigin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, withCredentials")
w.Header().Set("Access-Control-Allow-Methods", method) // use the endpoint's method: POST, GET, OPTIONS
You need to expose the endpoint where the frontend will redirect the user and set the cookie in the response. Instead of setting the domain of the API by hand, you can omit it, the browser will fill it with the domain automatically.
To handle the CORS and let JS send the cookie successfully, you will have to set the SameSite=None and Secure attributes in the cookie and serve the API over https (I used ngrok to make it simple).
Like so
func SetCookie(w *http.ResponseWriter, email string) string {
val := uuid.NewString()
http.SetCookie(*w, &http.Cookie{
Name: "goCookie",
Value: val,
SameSite: http.SameSiteNoneMode,
Secure: true,
Path: "/",
})
// rest of the code
}
I recommend you also read the difference between using localStorage and document.cookie, it was one of the problems I had.
Hope this helps.

Sign in with Google - What should I do with `nonce`?

What I'm doing now:
Using the JavaScript API to render the button on my web page.
When the Sign in with Google flow is complete, my client-side JavaScript callback is called.
That callback sends the given .credentials string to my server.
The backend server (Node.js) calls the google-auth-library library's OAuth2Client.verifyIdtoken method on the .credentials string, which returns the user's email address (among other things), which my server uses to verify the user and create a session.
Everything works, but I'm wondering if there are any security concerns I'm missing. In particular there's a nonce field. The docs (link) don't explain how to use it.
Note: I'm using "Sign in with Google" and not the deprecated "Google Sign-In".
Edit: I'm familiar with the concept of nonces and have used them when doing the OAuth 2 server-side flow myself. What I can't figure out is how the Sign in with Google SDK expects me to use its nonce parameter with the flow above, where I'm using both their client-side and server-side SDKs.
Nonces are used as a CSRF-prevention method. When you make a request to Google, you include a nonce, and when authentication is complete, Google will send the same nonce back. The magic in this method is that if the nonce does not match what you sent then you can ignore the response, because it was probably spoofed.
Read more about CSRF here: https://owasp.org/www-community/attacks/csrf
Nonces are usually crytographically secure random strings/bytes.
I use crypto-random-string as a base to generate nonces, but any package with this functionality should suffice.
Sometimes I store nonces with a TTL in Redis, but other times I store nonces with an ID attached to the request so I can later verify it.
I'm telling you this since it took a bit long for me to figure out this nonce stuff :P
Using the example from Google's website (https://developers.google.com/identity/one-tap/android/idtoken-auth), I added the code for the nonce:
const nonce = '...'; // Supplied by client in addition to token
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
});
const payload = ticket.getPayload();
const serverNonce = payload['nonce'];
if (nonce != serverNonce) {
// Return an error
}
const userid = payload['sub'];
// If request specified a G Suite domain:
// const domain = payload['hd'];
}
verify().catch(console.error);

How to set Authorization header while calling "callable function" on Firebase

Basically my problem is, I have my callable functions on Firebase where I want to use "context" to identify if the user is authenticated or not. In the front-end I am logging in user using Firebase authentication (which is an http function on firebase), and as I result I get my user token (which should be used as a Bearer token in the authorization header). The problem is I am not sure how to set the header when I sign in the user so that my "context.auth" would contain the logged in user info rather than being empty. I use firebase.functions().httpsCallable('myFunction'); as the document suggests to make the call from front-end where the problem is even though I logged in before making this call, my context is null.
To give more context think about the following scenario,
//Backend (deployed to cloud functions)
exports.signout = functions.https.onCall((data, context) => {
if(context.auth){
//do signout stuff and return true
}
else{
//not logged in so you can't sign out return false
}
});
//Client
let signout = firebase.functions().httpsCallable('signout');
signout()
.then(res => console.log("signed out"))
.catch(err => console.log(err))
So simply put, while making the httpsCallable('signout') in client, I should have the user token in the 'Authorization' header according to docs, so that I can access the context.auth from my callable function. The thing that I don't understand is how that header should be set there? The most logical thing is setting it on login, but it is not something like setting default header for axios since the call is not exactly an http request rather we use that special httpsCallable function. So how/when is that auth header should be set?
When you use a callable type function from a web or mobile client using the provided SDK, all of the details of the HTTP protocol are handled automatically. There's nothing you have to do to set any headers.
If the user is currently signed in at the time of the request, the SDK will add the authorization header automatically. If the user is signed out, then no header will be added. So, if you want to invoke signout with the authorization of the end user, you will obviously have to call it while they are signed in.
It sounds like you might have signed out the user before invoking the callable. In that case, your function will receive no user data.

Documentation for Airflow HTTP Operator/Sensor Extra Options?

I'm trying to read into the extra_options setting for Airflow to see what properties are possible to set (mainly interested in http timeout). I can't find any supporting documentation for this specific param anywhere: https://airflow.readthedocs.io/en/1.9.0/code.html?highlight=requests#airflow.operators.SimpleHttpOperator.
Has anyone worked with this before and is able to help?
According to source code (airflow.hooks.http_hook.HttpHook.run_and_check) extra_options uses these parameters:
response = session.send(
prepped_request,
stream=extra_options.get("stream", False),
verify=extra_options.get("verify", False),
proxies=extra_options.get("proxies", {}),
cert=extra_options.get("cert"),
timeout=extra_options.get("timeout"),
allow_redirects=extra_options.get("allow_redirects", True))
You can read more about them in requests library docs:
stream – (optional) whether to immediately download the response content. Defaults to False.
verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True.
proxies – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy.
cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
timeout (float or tuple) – (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.
allow_redirects (bool) – (optional) Set to True by default.
Following this trail of links in Airflow's source-code, you can easily determine what all things can be passed in SimpleHttpOperator, or more specifically, in extra field of Http Connection. I'm hereby adding trail of calls in Airflow's source that I used to trace the usage of extra_options
extra_options are passed to run() method of HttpHook
run() method of HttpHook passes those extra_options to run_and_check() method
run_and_check() method extracts variety of information from extra_options, as shown in the source-code snippet below
try:
response = session.send(
prepped_request,
stream=extra_options.get("stream", False),
verify=extra_options.get("verify", False),
proxies=extra_options.get("proxies", {}),
cert=extra_options.get("cert"),
timeout=extra_options.get("timeout"),
allow_redirects=extra_options.get("allow_redirects", True))
if extra_options.get('check_response', True):
self.check_response(response)
return response
except requests.exceptions.ConnectionError as ex:
self.log.warning(str(ex) + ' Tenacity will retry to execute the operation')
raise ex

Meteor.user() on iron-router server side

How can check, on server side route, if user is logged?
I would add check on 'before', but Metor.user() don't work here.
thanks in advance.
p.s. I have found How to get Meteor.user() to return on the server side?, but not work on iron-router
I'm afraid that this is not possible. I guess that the problem comes from the fact that you're trying to connect to the server with two different protocols - both literally and in logically - so there is no obvious way to relate this two actions.
There is, however, a pretty simple solution that may suit your needs. You'll need to develop a simple system of privileges tokens, or secret keys, or whatever you call them. First, create a server method
var Secrets = new Meteor.Collection("secrets"); // only on server!!!
Meteor.methods({
getSecretKey: function () {
if (!this.userId)
// check if the user has privileges
throw Meteor.Error(403);
return Secrets.insert({_id: Random.id(), user: this.userId});
},
});
Then, you can now use it on the client to get the secretKey which attach to your AJAX request (or something), either within the HTTP header or in the URL itself. Fear not!
They will all be encrypted if you're using HTTPS.
On the server side you can now retrieve the secretKey from the incoming request and check if it is present in the Secrets collection. You'll know then if the user is granted certain privileges or not.
Also you may want to remove your secret keys from the collection after some time for safety reasons.
If what you're looking to do is to authenticate the Meteor.user making the request, I'm currently doing this within the context of IronRouter.route(). The request must be made with a valid user ID and auth token in the header. I call this function from within Router.route(), which then gives me access to this.user:
###
Verify the request is being made by an actively logged in user
#context: IronRouter.Router.route()
###
authenticate = ->
# Get the auth info from header
userId = this.request.headers['x-user-id']
loginToken = this.request.headers['x-auth-token']
# Get the user from the database
if userId and loginToken
user = Meteor.users.findOne {'_id': userId, 'services.resume.loginTokens.token': loginToken}
# Return an error if the login token does not match any belonging to the user
if not user
respond.call this, {success: false, message: "You must be logged in to do this."}, 401
# Attach the user to the context so they can be accessed at this.user within route
this.user = user
###
Respond to an HTTP request
#context: IronRouter.Router.route()
###
respond = (body, statusCode=200, headers={'Content-Type':'text/json'}) ->
this.response.writeHead statusCode, headers
this.response.write(JSON.stringify(body))
this.response.end()
This code was heavily inspired by RestStop and RestStop2. It's part of a meteor package for writing REST APIs in Meteor 0.9.0+ (built on top of Iron Router). You can check out the complete source code here:
https://github.com/krose72205/meteor-restivus

Resources