Code Monkey home page Code Monkey logo

securecookie's People

Contributors

0x434d53 avatar abduelhamit avatar coreydaley avatar cyx avatar dchest avatar dominikh avatar elithrar avatar filosottile avatar flibustenet avatar hjr265 avatar jtdowney avatar kisielk avatar moraes avatar s7v7nislands avatar tflyons avatar vvvvv avatar wessie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

securecookie's Issues

Read the cookie from a browser?

I'm trying to read a secure cookie from the browser (just signed, not encrypted). The Base64 algorithm looks different from the native atob function...

Anyone tried this before?

What happen if MAC contains | ?

In the functions Encode/Decode, I see that you just concat (by fmt.Sprintf) and split (by bytes.SplitN) MAC to/from the buffer, so It will fail in case MAC contains '|' ? or It will never happen?

Update: Sorry, I mess the document: the last subslice will be the unsplit remainder

securecookie: base64 decode failed - caused by: illegal base64 data at input byte 216

Code

Session store

secret := securecookie.GenerateRandomKey(64)
if secret == nil {
	glg.Fatalf("The system random number generator failed")
}
srv.sessionStore = sessions.NewCookieStore(secret)

Session get

func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
	sess, err := s.sessionStore.Get(r, sessionCookieName)
	glg.Infof("Session is new: %v", sess.IsNew)
	if err != nil {
		glg.Errorf("read session: %v", err)
		sess, err = s.sessionStore.New(r, sessionCookieName)
		if err != nil {
			glg.Errorf("new session: %v", err)
			return
		}
	}
}

Output

2018-08-30 16:59:24     [INFO]: Session is new: true
2018-08-30 16:52:10     [ERR]:  read session: securecookie: base64 decode failed - caused by: illegal base64 data at input byte 216
2018-08-30 16:52:10     [ERR]:  new session: securecookie: base64 decode failed - caused by: illegal base64 data at input byte 216

At the point where this error occurs, the session is new and no data has been written into it's Values whatsoever.
I can't explain this error, and hoped maybe one of you can help me here?
I'd be happy to provide further information.

[feature] Support Nonce Misuse-Resistant Authenticated Encryption

Is your feature request related to a problem? Please describe.

The current algorithms available to securecookie are susceptible to nonce-reuse issues under certain conditions. I know this is very much on the radar 1,2 of the maintainers, but the effort seems tied to a v2 which I'm not sure of the status of.

Describe the solution you'd like

I'd like for sessions to use a non misuse-resistant algorithm. Options include:

XChaCha20-Poly1305 seems like the best current option. It currently exists in /x/crypto, implements the aead interface, is relatively fast (no AES-NI 😭 ), and is ubiquitous.

Describe alternatives you've considered

Reinvent the wheel and reimplement/fork my own sessions package. Which, you know. Meh.

Of course, I'd be happy to help but didn't want to step on toes if this is part of a larger effort.

EncodeMulti masks reason for errors

As reported on the mailing list in https://groups.google.com/d/topic/gorilla-web/dw9NNfkftJU/discussion

The fix is to change EncodeMulti to do something like:

func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) {
            for _, codec := range codecs {
                            if encoded, err := codec.Encode(name, value); err == nil {
                                            return encoded, nil
                            } else {
                                return "", err  // added this line
                            }
            }
            return "", errors.New("securecookie: the value could not be encoded")
 }

Of course if the intent is to try all the codecs till one succeeds then this becomes trickier, as this will return a failure upon the first failing codec.

Expose error types?

It seems like the ideal behavior for a cookie w/ an expired timestamp would be for me to consider it equivalent to http.ErrNoCookie, but right now I can't find a clean way to check for that, since the types of errors are all private.

Am I missing a better workflow or existing clean way to check for this?

[FEATURE] Change signature of GenerateRandomKey

Is there an existing feature request for this?

  • I have searched the existing feature requests

Is your feature request related to a problem? Please describe.

It is not very secure by default that people are expected to check if GenerateRandomKey returns nil on an error and I've just made a friend aware of this that he missed checking it.

Describe the solution that you would like.

I would like to change the signate of GenerateRandomKey to (length int) ([]byte, err) to allow proper error checking and forwarding.

Describe alternatives you have considered.

None

Anything else?

I know that the error that could be created here is rare and unrealistic but cryptography that use nil for their secret on an error is pretty bad.

Also maybe this warrants a minor or major bump, not sure how strict the project is here.

NopEncoder does not Deserialize properly.

The NopEncoder checks that the dst you give it is of type []byte. It then sets dst=src which effectively only changes the local parameter. The caller of Decode cannot access the value it sets because it only affects the local parameter.

In order for it to work, the type assertion should be for (*[]byte) and it should point dst at src.

PR incoming.

valid semver tag for vgo

The current tag v1.1 is not compatible with vgo. Can it be changed to v1.1.0 ?
When securecookie has no dependencies, i believe it doesn't need a go.mod file (i'm not sure).
I think it will also help the next step to v2

The related issue at vgo:
golang/go#23954

Invalid value %v

It is possible to generate an error yielding the literal message "securecookie: invalid value %v" where the %v is a string literal.

Is the intent of this message to send back the value of parts, or is the %v literal intended?

How to handle error "securecookie: expired timestamp"

I get error securecookie: expired timestamp even though I don't set an expiration date on the cookie. (I suspect there's a date in the encrypted cookie.) Here is my logic:

	co, err := sc.Encode("user", user.ID)
	if err != nil {
		return errors.Wrap(err, "failed to encode the token")
	}

	http.SetCookie(w, &http.Cookie{
		Name:  "user",
		Path:  "/",
		Value: co,
	})

What am I supposed to do with this error?

The errTimestampExpired is not exported from the package, so that doesn't give me a good way to check whether an error is indeed expiration error. What should a server do when they get this error? Clear cookies to unblock the user?

Cookie not returned from the browser

Hello,

I am having issues using securecookie. When I encode a value and send it to the browser, it is sometimes not returning it back. Seems to me like the browser doesn't like some of the characters in the encoded cookie value. I am using Google Chrome, up to date.

Tried replacing base64 with base32.StdEncoding in this package and also replacing the padding = with 0, which is ok for base32.StdEncoding, and it all started working.

So, I am basically asking where the issues is. How come this package is working for other people?

In case I don't want to fork this package, what am I supposed to do? Encode the value returned from securecookie with base32? That will only increase the cookie size, although it is not really dramatic for my use case...

Thanks!

Continuous Fuzzing

Hi, I'm Yevgeny Pats Founder of Fuzzit - Continuous fuzzing as a service platform.

I saw that you implemented Fuzz targets but they are currently not running as part of the CI.

We have a free plan for OSS and I would be happy to contribute a PR if that's interesting.
The PR will include the following

  • Continuous Fuzzing of master branch which will generate new corpus and look for new crashes
  • Regression on every PR that will run the fuzzers through all the generated corpus and fixed crashes from previous step. This will prevent new or old bugs from crippling into master.

You can see our basic example here and you can see an example of "in the wild" integration here.

Let me know if this is something worth working on.

Cheers,
Yevgeny

Cookie Name in Encode function optional ?

For the following example

s is *securecookie.SecureCookie

plainValue := map[string]string{"value": "__PLAIN__VALUE",}
encodedValue, errCookieEncode := s.Encode("cookie-name, plainValue)
    if errCookieEncode != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Println(errCookieEncode)
	} else{
		cookie := &http.Cookie{
			Name:  "different-cookie-name",
			Value: encodedValue,
			Path:  "/",
		} 
		http.SetCookie(w, cookie)
		w.WriteHeader(http.StatusOK)
	}

Does cookie-name have to present as different-cookie-name replaces it eventually ?

securecookie: v2

Preface: we're thinking about what a gorilla/sessions v2 would look like. This naturally extends to securecookie, which provides a lot of the underlying implementation.

Key areas for improvement in v2:

  • Simplify the error interfaces: multi-error and the error types are overly complex and lead to a lot of error-handling code downstream. Generalizing to user-error (and making it harder to provide bad keys and input!), authentication error (crypto) and data error (marshalling bugs) should be enough.
  • Replace AES-CTR + HMAC-SHA-256 with XSalsa20Poly1305 (via nacl/secretbox). This is an AEAD construct that provides encryption+authentication together, securely.
  • Make the key rotation interface better (variadic is confusing: move to an Option struct)
  • Keep all of the great fuzzing tests.

securecookie: AES-CTR origin

Hello,

Quick question about the encryption. Is there a discussed research (or tests) for using AES-CTR + SHA256 approach instead of AES-GCM? For evaluation purposes for development.

Thanks in adv.

Document using multiple codecs in the readme

Is your feature request related to a problem? Please describe.

I'd like the ability to more easily rotate keys by being able to add a list of valid decryption keys.

Describe the solution you'd like

Change
New(hashKey, blockKey []byte) to
New(hashKey, blockKey []byte, decodeKeys ...[]byte) and add a check that if a cookie cannot be decoded with the hashKey to try with the decode keys until one matches or all fail. This would allow users to have some logic like
New(todaysKey(), nil, tomorrowsKey(), yesterdaysKey()) and rotate keys automatically even in a distributed environment. It would also preserve backwards compatibility with New(hashKey, nil).

Describe alternatives you've considered

There's the obvious, just don't rotate the keys. Or coordinate a failover mechanism by chaining decodes using multiple secure cookies. This seems like a more straightforward approach however.

Asymmetric cookie encryption

Is it possible to use asymmetric encryption keys with securecookie, so that cookies generated by one server can be decrypted by another?

difference to JWT

Not really a bug or a feature request - but a request for clarification in the README.

Why would one use the this project over JWT?
JWT also supports signing and encryption - and is a standard.

I am not making a case for either - but it would be nice to read a position on this.

corresponding Java implementation

Excuse me, Does this algorithm have a corresponding Java implementation?

There is a Go Projection encode cookie by using this algorithm, and now , I want decode the cookie in Java Projection.

I can not find a java lib about decoding cookie by using this algorithm.

Please Help Me~~~

securecookie: error - caused by: securecookie: error - caused by: gob: decoding into local type *map[string]string, received remote type string

I'm trying to decode the cookie encoded by securecookie. Below is how it is encoded:
func SessionHandler(w http.ResponseWriter, accessToken string, hash []byte) { sc := securecookie.New(hash, nil) if encoded, err := sc.Encode("access_token", accessToken); err == nil { cookie := &http.Cookie{ Name: "access_token", Value: encoded, HttpOnly: true, Expires: time.Now().Local().Add(time.Hour * time.Duration(1)), } http.SetCookie(w, cookie) } }

And below is how it is decoded.
func TokenExtractor(r *http.Request, hash []byte) (string, error) { sc := securecookie.New(hash, nil) cookie, err := r.Cookie("access_token") if err != nil { return "", err } value := make(map[string]string) err = sc.Decode("access_token", cookie.Value, &value) return value["access_token"], err }

Using the TokenExtractor
if hashKey, err := cfg.CookieKey("hash"); err == nil { tkn, err := TokenExtractor(r, hashKey) if err != nil { log.Println(err) } log.Println(tkn) }

I'm getting this error:
securecookie: error - caused by: securecookie: error - caused by: gob: decoding into local type *map[string]string, received remote type string

P.S: I'm sorry I'm not sure how to format the code above properly here.

Expose errors

I was wondering if it might be a good idea to expose the error values of this package.

For example, instead of returning errors.New("securecookie: the value is not valid") at line 259, the error value could be declared at the top of the source code file as (may be) ErrInvalid, and then that could be returned. Other relevant errors may be exposed in a similar way.

This way, consumers of this package (or the sessions package) can determine what exactly went wrong while decoding the cookie when an error occurs.

I felt the need for this while working on a webapp server where cookie key is generated randomly on first start and stored for subsequent sessions. However, once the database is emptied, the key is regenerated and that is where the app breaks since the sessions package keeps passing the error mentioned above.

I am not certain if there is a more elegant way to address this; or may be I am doing something the wrong way to start with.

If you want, I can send a pull request your way implementing this change.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.