0xnoob
0xnoob

Reputation: 1057

What is the purpose of the secret in express-session middleware?

I was reading the express-session README, which says about the secret:

This is the secret used to sign the session ID cookie. [...]

Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the genid option).

https://github.com/expressjs/session#secret

tbh: I don't really understand that.

I thought the purpose of a secret is to be used together with the session ID as parameters to some kind of hash-function, to generate a signature (as in hash(secret, sessionID) => signature) and that signature is appended on the session ID-value in the cookie.

Hence, that in case someone guessed a correct session ID, it still wouldn't work because the signature wouldn't match?

What is the secret actually used for?

Upvotes: 1

Views: 1411

Answers (1)

jfriend00
jfriend00

Reputation: 707966

When questions like this arise, it's usually best to just go look at the source code and see how the secret is used. This is one of the advantages of using open-source code.

In the express-session code, the secret is used to "digitally sign" the value of the cookie as you can see in the express-session code here. This allows the session code to detect if a cookie value has been tampered with or if it's still the authentic value originally set on the server and it makes them harder to "guess" in a brute force session attack.

Upon reading the cookie value later (in the code here), that value is checked to see if it has been properly signed with the right secret. If not, the cookie value is discarded (not used).

This is a means of preventing hackers from making up their own cookie values or modifying cookie values since only values that were signed with the appropriate secret will test as valid.

The process of signing also has a side benefit in that it makes the value longer and somewhat random-looking, so it obscures the underlying value making it harder to guess. The classic example would if the underlying session id was simply a monotonically increasing number, then it would be easy to guess future or previous session values. But, once it is signed, it no longer looks like a simple monotonically increasing number and it is not easy to guess past or future signed session values. Though express-session uses a 24 byte uid as its session id, when signing it, the value extends to much, much longer which makes it even harder to guess and find valid sessions (the signed cookie value I looked at was 80 bytes long (after some encoding).

FYI, here's a simplified discussion of "why sign the cookie?": https://github.com/expressjs/session/issues/68 from the express-session github repository.

Upvotes: 4

Related Questions