From 2cad923a33730d26ad7ac92979a00ba86a58f242 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Mon, 8 Jun 2020 20:33:02 +1000 Subject: [PATCH 001/329] New translations translation.lang.yaml (Romanian) --- languages/ro-RO.lang.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/languages/ro-RO.lang.yaml b/languages/ro-RO.lang.yaml index 16b87023..bca027c1 100644 --- a/languages/ro-RO.lang.yaml +++ b/languages/ro-RO.lang.yaml @@ -10,6 +10,6 @@ name: "Română" #code - this is what the language will be referred to in our list of languages code: "ro" #contributors - people who have contributed to this translation -contributors: "Bogdan Mințoi " +contributors: "Bogdan Mințoi \nEne Alin Gabriel " #incomplete - whether to mark this language as incomplete incomplete: true From 8de23ab6243d768166e3c90359edb8dd65a11ca9 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Mon, 8 Jun 2020 20:33:03 +1000 Subject: [PATCH 002/329] New translations chanserv.lang.json (Romanian) --- languages/ro-RO-chanserv.lang.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/ro-RO-chanserv.lang.json b/languages/ro-RO-chanserv.lang.json index e7b1bb48..b64f6090 100644 --- a/languages/ro-RO-chanserv.lang.json +++ b/languages/ro-RO-chanserv.lang.json @@ -4,7 +4,7 @@ "$bGET$b queries the current values of a channel's settings": "$bGET$b interoghează valorile actuale ale setărilor unui canal", "$bHISTORY$b\n'history' lets you control how channel history is stored. Your options are:\n1. 'off' [no history]\n2. 'ephemeral' [a limited amount of temporary history, not stored on disk]\n3. 'on' [history stored in a permanent database, if available]\n4. 'default' [use the server default]": "$bHISTORY$b\n'history' îți permite să controlezi felul în care istoricul unui canal e stocat. Ai la dispoziție următoarele opțiuni:\n1. 'off' [fără niciun fel de istoric]\n2. 'ephemeral' [doar un strop de istoric temporar, nu este stocat pe disc]\n3. 'on' [istoricul este stocat într-o bază de date persistentă, dacă opțiunea este posibilă]\n4. 'default' [folosește opțiunea implicită, a serverului]", "$bINFO$b displays info about a registered channel.": "$bINFO$b afișează informații despre un canal înregistrat.", - "$bLIST$b searches the list of registered channels.": "", + "$bLIST$b searches the list of registered channels.": "$bLIST$b caută lista de canale înregistrate.$bLIST$.", "$bOP$b makes the given user (or yourself) a channel admin.": "$bOP$b oferă utilizatorului specificat (sau ție) drepturi de administrator de canal.", "$bPURGE$b blacklists a channel from the server.": "$bPURGE$b adaugă la lista neagră un canal din server.", "$bREGISTER$b lets you own a given channel.": "$bREGISTER$b îți permite să deții un canal specificat.", @@ -18,7 +18,7 @@ "Syntax: $bAMODE #channel [mode change] [account]$b\n\nAMODE lists or modifies persistent mode settings that affect channel members.\nFor example, $bAMODE #channel +o dan$b grants the the holder of the \"dan\"\naccount the +o operator mode every time they join #channel. To list current\naccounts and modes, use $bAMODE #channel$b. Note that users are always\nreferenced by their registered account names, not their nicknames.": "Sintaxă: $bAMODE #canal [modificare fanion] [cont]$b\n\nComanda AMODE afișează sau modifică setările persistente ale fanioanelor ce afectează membrii canalului.\nDe exemplu, $bAMODE #canal +o dan$b îi oferă deținătorului contului \"dan\", statutul de\noperator de canal, de fiecare dată când va intra pe #canal. Pentru a afișa conturile și fanioanele\nactuale, folosește $bAMODE #canal$b. De reținut faptul că utilizatorii sunt asociați cu numele \nconturilor înregistrate, și nu cu pseudonimele folosite.", "Syntax: $bCLEAR #channel target$b\n\nCLEAR removes users or settings from a channel. Specifically:\n\n$bCLEAR #channel users$b kicks all users except for you.\n$bCLEAR #channel access$b resets all stored bans, invites, ban exceptions,\nand persistent user-mode grants made with CS AMODE.": "Sintaxă: $bCLEAR #canal țintă$b\n\nCLEAR înlătură setările sau utilizatorii unui canal. Mai exact:\n\n$bCLEAR #canal users$b înlătură toți utilizatorii canalului, în afară de tine.\n$bCLEAR #canal access$b resetează toate interdicțiile existente pe canal, invitațiile, excepțiile la ban și modurile de utilizator persistente, cu ajutorul CS AMODE.", "Syntax: $bGET #channel $b\n\nGET queries the current values of the channel settings. For more information\non the settings and their possible values, see HELP SET.": "Sintaxă: $bGET #canal $b\n\nComanda GET interoghează setările existente, ale unui canal. Pentru mai multe\ninformații, folosește comanda /HELP SET.", - "Syntax: $bLIST [regex]$b\n\nLIST returns the list of registered channels, which match the given regex.\nIf no regex is provided, all registered channels are returned.": "", + "Syntax: $bLIST [regex]$b\n\nLIST returns the list of registered channels, which match the given regex.\nIf no regex is provided, all registered channels are returned.": "Syntax: $bLIST [regex]$b\n\nLIST înapoiază lista de canale înregistrate, care se potrivesc cu regex dat.\nDaca nici un regex nu este dat, toate canalele înregistrate sunt înapoiate.", "Syntax: $bOP #channel [nickname]$b\n\nOP makes the given nickname, or yourself, a channel admin. You can only use\nthis command if you're the founder of the channel.": "Sintaxă: $bOP #canal [pseudonim]$b\n\nOP oferă pseudonimului furnizat, sau ție, dacă [pseudonim] nu este specificat, privilegii\nde administrator de canal. Poți utiliza această comandă doar dacă ai fondat canalul.", "Syntax: $bPURGE #channel [reason]$b\n\nPURGE blacklists a channel from the server, making it impossible to join\nor otherwise interact with the channel. If the channel currently has members,\nthey will be kicked from it. PURGE may also be applied preemptively to\nchannels that do not currently have members.": "Sintxă: $bPURGE #canal [motiv]$b\n\nPURGE adaugă la lista neagră un canal din server, astfel că niciun utilizator nu mai poate intra pe canalul respectiv, sau să interacționeze în vreun fel cu canalul în cauză. Dacă, în momentul comenzii, se află utilizatori în canal, vor fi scoși afară automat.\nComanda PURGE poate fi utilizată și în mod preventiv, pentru canalele fără utilizatori.", "Syntax: $bREGISTER #channel$b\n\nREGISTER lets you own the given channel. If you rejoin this channel, you'll be\ngiven admin privs on it. Modes set on the channel and the topic will also be\nremembered.": "Sintaxă: $bREGISTER #canal$b\n\nComanda REGISTER îți permite să deții propriul canal. Dacă revii pe canal, ulterior, vei\nprimi privilegii de administrator al canalului. Fanioanele setate pe canal, precum și\ntopica, vor fi reținute.", From 00e2c2816b1635b464721582b9ab1946304fc669 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 8 Jun 2020 23:38:10 -0400 Subject: [PATCH 003/329] use strings.Builder instead of bytes.Buffer where applicable --- irc/channel.go | 3 +-- irc/utils/glob.go | 8 ++++---- irc/utils/text.go | 3 +-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/irc/channel.go b/irc/channel.go index 947ad9d4..1692eb40 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -6,7 +6,6 @@ package irc import ( - "bytes" "fmt" "strconv" "strings" @@ -447,7 +446,7 @@ func (channel *Channel) Names(client *Client, rb *ResponseBuffer) { maxNamLen := 480 - len(client.server.name) - len(client.Nick()) var namesLines []string - var buffer bytes.Buffer + var buffer strings.Builder if isJoined || !channel.flags.HasMode(modes.Secret) || isOper { for _, target := range channel.Members() { var nick string diff --git a/irc/utils/glob.go b/irc/utils/glob.go index 04ee6116..5ad98f44 100644 --- a/irc/utils/glob.go +++ b/irc/utils/glob.go @@ -4,14 +4,14 @@ package utils import ( - "bytes" "regexp" "regexp/syntax" + "strings" ) // yet another glob implementation in Go -func addRegexp(buf *bytes.Buffer, glob string, submatch bool) (err error) { +func addRegexp(buf *strings.Builder, glob string, submatch bool) (err error) { for _, r := range glob { switch r { case '*': @@ -36,7 +36,7 @@ func addRegexp(buf *bytes.Buffer, glob string, submatch bool) (err error) { } func CompileGlob(glob string, submatch bool) (result *regexp.Regexp, err error) { - var buf bytes.Buffer + var buf strings.Builder buf.WriteByte('^') err = addRegexp(&buf, glob, submatch) if err != nil { @@ -50,7 +50,7 @@ func CompileGlob(glob string, submatch bool) (result *regexp.Regexp, err error) // This is used for channel ban/invite/exception lists. It's applicable to k-lines // but we're not using it there yet. func CompileMasks(masks []string) (result *regexp.Regexp, err error) { - var buf bytes.Buffer + var buf strings.Builder buf.WriteString("^(") for i, mask := range masks { err = addRegexp(&buf, mask, false) diff --git a/irc/utils/text.go b/irc/utils/text.go index 82b07fdb..bffa7a34 100644 --- a/irc/utils/text.go +++ b/irc/utils/text.go @@ -4,7 +4,6 @@ package utils import ( - "bytes" "strings" "time" ) @@ -98,7 +97,7 @@ func (sm *SplitMessage) Is512() bool { type TokenLineBuilder struct { lineLen int delim string - buf bytes.Buffer + buf strings.Builder result []string } From d33a084bb6675bc9bb38cd4cc264ec71b76e2a6e Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 9 Jun 2020 18:17:48 -0400 Subject: [PATCH 004/329] fix #1125 --- irc/accounts.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/irc/accounts.go b/irc/accounts.go index 41f93809..4f70079d 100644 --- a/irc/accounts.go +++ b/irc/accounts.go @@ -1763,7 +1763,7 @@ func (am *AccountManager) applyVHostInfo(client *Client, info VHostInfo) { } oldNickmask := client.NickMaskString() updated := client.SetVHost(vhost) - if updated { + if updated && client.Registered() { // TODO: doing I/O here is kind of a kludge client.sendChghost(oldNickmask, client.Hostname()) } From 218bea5a3e4077b3d64224c764dc23016e1e229f Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Fri, 12 Jun 2020 15:51:48 -0400 Subject: [PATCH 005/329] fix #843 --- irc/accounts.go | 26 ++++++++++-------- irc/client.go | 71 ++++++++++++++++++++++++++++++++++++++++++------- irc/errors.go | 9 +++++++ irc/getters.go | 18 +++++++++---- irc/handlers.go | 57 +++++++++++++++++++++++++++++---------- irc/nickserv.go | 13 ++++----- 6 files changed, 146 insertions(+), 48 deletions(-) diff --git a/irc/accounts.go b/irc/accounts.go index 4f70079d..530d2e34 100644 --- a/irc/accounts.go +++ b/irc/accounts.go @@ -617,11 +617,12 @@ func (am *AccountManager) loadModes(account string) (uModes modes.Modes) { return } -func (am *AccountManager) saveLastSeen(account string, lastSeen time.Time) { +func (am *AccountManager) saveLastSeen(account string, lastSeen map[string]time.Time) { key := fmt.Sprintf(keyAccountLastSeen, account) var val string - if !lastSeen.IsZero() { - val = strconv.FormatInt(lastSeen.UnixNano(), 10) + if len(lastSeen) != 0 { + text, _ := json.Marshal(lastSeen) + val = string(text) } am.server.store.Update(func(tx *buntdb.Tx) error { if val != "" { @@ -633,20 +634,19 @@ func (am *AccountManager) saveLastSeen(account string, lastSeen time.Time) { }) } -func (am *AccountManager) loadLastSeen(account string) (lastSeen time.Time) { +func (am *AccountManager) loadLastSeen(account string) (lastSeen map[string]time.Time) { key := fmt.Sprintf(keyAccountLastSeen, account) var lsText string am.server.store.Update(func(tx *buntdb.Tx) error { lsText, _ = tx.Get(key) - // XXX clear this on startup, because it's not clear when it's - // going to be overwritten, and restarting the server twice in a row - // could result in a large amount of duplicated history replay - tx.Delete(key) return nil }) - lsNum, err := strconv.ParseInt(lsText, 10, 64) - if err == nil { - return time.Unix(0, lsNum).UTC() + if lsText == "" { + return nil + } + err := json.Unmarshal([]byte(lsText), &lastSeen) + if err != nil { + return nil } return } @@ -1052,6 +1052,10 @@ func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName s } } + if throttled, remainingTime := client.checkLoginThrottle(); throttled { + return &ThrottleError{remainingTime} + } + var account ClientAccount defer func() { diff --git a/irc/client.go b/irc/client.go index 599aa9ee..669016dd 100644 --- a/irc/client.go +++ b/irc/client.go @@ -30,6 +30,11 @@ const ( // IdentTimeout is how long before our ident (username) check times out. IdentTimeout = time.Second + 500*time.Millisecond IRCv3TimestampFormat = utils.IRCv3TimestampFormat + // limit the number of device IDs a client can use, as a DoS mitigation + maxDeviceIDsPerClient = 64 + // controls how often often we write an autoreplay-missed client's + // deviceid->lastseentime mapping to the database + lastSeenWriteInterval = time.Minute * 10 ) // ResumeDetails is a place to stash data at various stages of @@ -60,8 +65,9 @@ type Client struct { invitedTo map[string]bool isSTSOnly bool languages []string - lastActive time.Time // last time they sent a command that wasn't PONG or similar - lastSeen time.Time // last time they sent any kind of command + lastActive time.Time // last time they sent a command that wasn't PONG or similar + lastSeen map[string]time.Time // maps device ID (including "") to time of last received command + lastSeenLastWrite time.Time // last time `lastSeen` was written to the datastore loginThrottle connection_limits.GenericThrottle nick string nickCasefolded string @@ -112,6 +118,8 @@ const ( type Session struct { client *Client + deviceID string + ctime time.Time lastActive time.Time @@ -299,7 +307,7 @@ func (server *Server) RunClient(conn IRCConn) { // give them 1k of grace over the limit: socket := NewSocket(conn, config.Server.MaxSendQBytes) client := &Client{ - lastSeen: now, + lastSeen: make(map[string]time.Time), lastActive: now, channels: make(ChannelSet), ctime: now, @@ -358,11 +366,14 @@ func (server *Server) RunClient(conn IRCConn) { client.run(session) } -func (server *Server) AddAlwaysOnClient(account ClientAccount, chnames []string, lastSeen time.Time, uModes modes.Modes) { +func (server *Server) AddAlwaysOnClient(account ClientAccount, chnames []string, lastSeen map[string]time.Time, uModes modes.Modes) { now := time.Now().UTC() config := server.Config() - if lastSeen.IsZero() { - lastSeen = now + if lastSeen == nil { + lastSeen = make(map[string]time.Time) + if account.Settings.AutoreplayMissed { + lastSeen[""] = now + } } client := &Client{ @@ -714,14 +725,39 @@ func (client *Client) playReattachMessages(session *Session) { // at this time, modulo network latency and fakelag). `active` means not a PING or suchlike // (i.e. the user should be sitting in front of their client). func (client *Client) Touch(active bool, session *Session) { + var markDirty bool now := time.Now().UTC() client.stateMutex.Lock() - defer client.stateMutex.Unlock() - client.lastSeen = now if active { client.lastActive = now session.lastActive = now } + if client.accountSettings.AutoreplayMissed { + client.setLastSeen(now, session.deviceID) + if now.Sub(client.lastSeenLastWrite) > lastSeenWriteInterval { + markDirty = true + client.lastSeenLastWrite = now + } + } + client.stateMutex.Unlock() + if markDirty { + client.markDirty(IncludeLastSeen) + } +} + +func (client *Client) setLastSeen(now time.Time, deviceID string) { + client.lastSeen[deviceID] = now + // evict the least-recently-used entry if necessary + if maxDeviceIDsPerClient < len(client.lastSeen) { + var minLastSeen time.Time + var minClientId string + for deviceID, lastSeen := range client.lastSeen { + if minLastSeen.IsZero() || lastSeen.Before(minLastSeen) { + minClientId, minLastSeen = deviceID, lastSeen + } + } + delete(client.lastSeen, minClientId) + } } // Ping sends the client a PING message. @@ -1604,6 +1640,12 @@ func (client *Client) attemptAutoOper(session *Session) { } } +func (client *Client) checkLoginThrottle() (throttled bool, remainingTime time.Duration) { + client.stateMutex.Lock() + defer client.stateMutex.Unlock() + return client.loginThrottle.Touch() +} + func (client *Client) historyStatus(config *Config) (status HistoryStatus, target string) { if !config.History.Enabled { return HistoryDisabled, "" @@ -1624,6 +1666,16 @@ func (client *Client) historyStatus(config *Config) (status HistoryStatus, targe return } +func (client *Client) copyLastSeen() (result map[string]time.Time) { + client.stateMutex.RLock() + defer client.stateMutex.RUnlock() + result = make(map[string]time.Time, len(client.lastSeen)) + for id, lastSeen := range client.lastSeen { + result[id] = lastSeen + } + return +} + // these are bit flags indicating what part of the client status is "dirty" // and needs to be read from memory and written to the db const ( @@ -1669,7 +1721,6 @@ func (client *Client) performWrite() { dirtyBits := client.dirtyBits client.dirtyBits = 0 account := client.account - lastSeen := client.lastSeen client.stateMutex.Unlock() if account == "" { @@ -1686,7 +1737,7 @@ func (client *Client) performWrite() { client.server.accounts.saveChannels(account, channelNames) } if (dirtyBits & IncludeLastSeen) != 0 { - client.server.accounts.saveLastSeen(account, lastSeen) + client.server.accounts.saveLastSeen(account, client.copyLastSeen()) } if (dirtyBits & IncludeUserModes) != 0 { uModes := make(modes.Modes, 0, len(modes.SupportedUserModes)) diff --git a/irc/errors.go b/irc/errors.go index 364ebbbc..6f199677 100644 --- a/irc/errors.go +++ b/irc/errors.go @@ -8,6 +8,7 @@ package irc import ( "errors" "fmt" + "time" "github.com/oragono/oragono/irc/utils" ) @@ -89,6 +90,14 @@ func (ck *CertKeyError) Error() string { return fmt.Sprintf("Invalid TLS cert/key pair: %v", ck.Err) } +type ThrottleError struct { + time.Duration +} + +func (te *ThrottleError) Error() string { + return fmt.Sprintf(`Please wait at least %v and try again`, te.Duration) +} + // Config Errors var ( ErrDatastorePathMissing = errors.New("Datastore path missing") diff --git a/irc/getters.go b/irc/getters.go index d51bce87..8041134e 100644 --- a/irc/getters.go +++ b/irc/getters.go @@ -62,6 +62,7 @@ type SessionData struct { ip net.IP hostname string certfp string + deviceID string } func (client *Client) AllSessionData(currentSession *Session) (data []SessionData, currentIndex int) { @@ -79,6 +80,7 @@ func (client *Client) AllSessionData(currentSession *Session) (data []SessionDat ctime: session.ctime, hostname: session.rawHostname, certfp: session.certfp, + deviceID: session.deviceID, } if session.proxiedIP != nil { data[i].ip = session.proxiedIP @@ -103,7 +105,7 @@ func (client *Client) AddSession(session *Session) (success bool, numSessions in copy(newSessions, client.sessions) newSessions[len(newSessions)-1] = session if client.accountSettings.AutoreplayMissed { - lastSeen = client.lastSeen + lastSeen = client.lastSeen[session.deviceID] } client.sessions = newSessions if client.autoAway { @@ -324,17 +326,23 @@ func (client *Client) AccountSettings() (result AccountSettings) { func (client *Client) SetAccountSettings(settings AccountSettings) { // we mark dirty if the client is transitioning to always-on - markDirty := false + var becameAlwaysOn, autoreplayMissedDisabled bool alwaysOn := persistenceEnabled(client.server.Config().Accounts.Multiclient.AlwaysOn, settings.AlwaysOn) client.stateMutex.Lock() - client.accountSettings = settings if client.registered { - markDirty = !client.alwaysOn && alwaysOn + autoreplayMissedDisabled = (client.accountSettings.AutoreplayMissed && !settings.AutoreplayMissed) + becameAlwaysOn = (!client.alwaysOn && alwaysOn) client.alwaysOn = alwaysOn + if autoreplayMissedDisabled { + client.lastSeen = make(map[string]time.Time) + } } + client.accountSettings = settings client.stateMutex.Unlock() - if markDirty { + if becameAlwaysOn { client.markDirty(IncludeAllAttrs) + } else if autoreplayMissedDisabled { + client.markDirty(IncludeLastSeen) } } diff --git a/irc/handlers.go b/irc/handlers.go index c68b2170..f1639b7f 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -236,6 +236,11 @@ func authPlainHandler(server *Server, client *Client, mechanism string, value [] return false } + // see #843: strip the device ID for the benefit of clients that don't + // distinguish user/ident from account name + if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 { + authcid = authcid[:strudelIndex] + } password := string(splitValue[2]) err := server.accounts.AuthenticateByPassphrase(client, authcid, password) if err != nil { @@ -251,6 +256,10 @@ func authPlainHandler(server *Server, client *Client, mechanism string, value [] } func authErrorToMessage(server *Server, err error) (msg string) { + if throttled, ok := err.(*ThrottleError); ok { + return throttled.Error() + } + switch err { case errAccountDoesNotExist, errAccountUnverified, errAccountInvalidCredentials, errAuthzidAuthcidMismatch, errNickAccountMismatch: return err.Error() @@ -280,6 +289,11 @@ func authExternalHandler(server *Server, client *Client, mechanism string, value } if err == nil { + // see #843: strip the device ID for the benefit of clients that don't + // distinguish user/ident from account name + if strudelIndex := strings.IndexByte(authzid, '@'); strudelIndex != -1 { + authzid = authzid[:strudelIndex] + } err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid) } @@ -2180,8 +2194,8 @@ func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Resp rb.Add(nil, server.name, ERR_ALREADYREGISTRED, client.nick, client.t("You may not reregister")) return false } - // only give them one try to run the PASS command (all code paths end with this - // variable being set): + // only give them one try to run the PASS command (if a server password is set, + // then all code paths end with this variable being set): if rb.session.passStatus != serverPassUnsent { return false } @@ -2192,18 +2206,17 @@ func passHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Resp if config.Accounts.LoginViaPassCommand { colonIndex := strings.IndexByte(password, ':') if colonIndex != -1 && client.Account() == "" { - // TODO consolidate all login throttle checks into AccountManager - throttled, _ := client.loginThrottle.Touch() - if !throttled { - account, accountPass := password[:colonIndex], password[colonIndex+1:] - err := server.accounts.AuthenticateByPassphrase(client, account, accountPass) - if err == nil { - sendSuccessfulAccountAuth(client, rb, false, true) - // login-via-pass-command entails that we do not need to check - // an actual server password (either no password or skip-server-password) - rb.session.passStatus = serverPassSuccessful - return false - } + account, accountPass := password[:colonIndex], password[colonIndex+1:] + if strudelIndex := strings.IndexByte(account, '@'); strudelIndex != -1 { + account, rb.session.deviceID = account[:strudelIndex], account[strudelIndex+1:] + } + err := server.accounts.AuthenticateByPassphrase(client, account, accountPass) + if err == nil { + sendSuccessfulAccountAuth(client, rb, false, true) + // login-via-pass-command entails that we do not need to check + // an actual server password (either no password or skip-server-password) + rb.session.passStatus = serverPassSuccessful + return false } } } @@ -2521,6 +2534,22 @@ func userHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Resp return false } + // #843: we accept either: `USER user:pass@clientid` or `USER user@clientid` + if strudelIndex := strings.IndexByte(username, '@'); strudelIndex != -1 { + username, rb.session.deviceID = username[:strudelIndex], username[strudelIndex+1:] + if colonIndex := strings.IndexByte(username, ':'); colonIndex != -1 { + var password string + username, password = username[:colonIndex], username[colonIndex+1:] + err := server.accounts.AuthenticateByPassphrase(client, username, password) + if err == nil { + sendSuccessfulAccountAuth(client, rb, false, true) + } else { + // this is wrong, but send something for debugging that will show up in a raw transcript + rb.Add(nil, server.name, ERR_SASLFAIL, client.Nick(), client.t("SASL authentication failed")) + } + } + } + err := client.SetNames(username, realname, false) if err == errInvalidUsername { // if client's using a unicode nick or something weird, let's just set 'em up with a stock username instead. diff --git a/irc/nickserv.go b/irc/nickserv.go index 06b6609d..fd2f83fd 100644 --- a/irc/nickserv.go +++ b/irc/nickserv.go @@ -649,14 +649,11 @@ func nsGroupHandler(server *Server, client *Client, command string, params []str } func nsLoginThrottleCheck(client *Client, rb *ResponseBuffer) (success bool) { - client.stateMutex.Lock() - throttled, remainingTime := client.loginThrottle.Touch() - client.stateMutex.Unlock() + throttled, remainingTime := client.checkLoginThrottle() if throttled { nsNotice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime)) - return false } - return true + return !throttled } func nsIdentifyHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) { @@ -685,9 +682,6 @@ func nsIdentifyHandler(server *Server, client *Client, command string, params [] // try passphrase if passphrase != "" { - if !nsLoginThrottleCheck(client, rb) { - return - } err = server.accounts.AuthenticateByPassphrase(client, username, passphrase) loginSuccessful = (err == nil) } @@ -1070,6 +1064,9 @@ func nsSessionsHandler(server *Server, client *Client, command string, params [] } else { nsNotice(rb, fmt.Sprintf(client.t("Session %d:"), i+1)) } + if session.deviceID != "" { + nsNotice(rb, fmt.Sprintf(client.t("Device ID: %s"), session.deviceID)) + } nsNotice(rb, fmt.Sprintf(client.t("IP address: %s"), session.ip.String())) nsNotice(rb, fmt.Sprintf(client.t("Hostname: %s"), session.hostname)) nsNotice(rb, fmt.Sprintf(client.t("Created at: %s"), session.ctime.Format(time.RFC1123))) From df1be01f54634c69bfcb84ac2884bfe0afdb9832 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Sun, 14 Jun 2020 13:52:29 -0400 Subject: [PATCH 006/329] simplify lastSeen handling --- irc/client.go | 11 +++++------ irc/getters.go | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/irc/client.go b/irc/client.go index 669016dd..d733ee23 100644 --- a/irc/client.go +++ b/irc/client.go @@ -307,7 +307,6 @@ func (server *Server) RunClient(conn IRCConn) { // give them 1k of grace over the limit: socket := NewSocket(conn, config.Server.MaxSendQBytes) client := &Client{ - lastSeen: make(map[string]time.Time), lastActive: now, channels: make(ChannelSet), ctime: now, @@ -369,11 +368,8 @@ func (server *Server) RunClient(conn IRCConn) { func (server *Server) AddAlwaysOnClient(account ClientAccount, chnames []string, lastSeen map[string]time.Time, uModes modes.Modes) { now := time.Now().UTC() config := server.Config() - if lastSeen == nil { - lastSeen = make(map[string]time.Time) - if account.Settings.AutoreplayMissed { - lastSeen[""] = now - } + if lastSeen == nil && account.Settings.AutoreplayMissed { + lastSeen = map[string]time.Time{"": now} } client := &Client{ @@ -746,6 +742,9 @@ func (client *Client) Touch(active bool, session *Session) { } func (client *Client) setLastSeen(now time.Time, deviceID string) { + if client.lastSeen == nil { + client.lastSeen = make(map[string]time.Time) + } client.lastSeen[deviceID] = now // evict the least-recently-used entry if necessary if maxDeviceIDsPerClient < len(client.lastSeen) { diff --git a/irc/getters.go b/irc/getters.go index 8041134e..1d2038f3 100644 --- a/irc/getters.go +++ b/irc/getters.go @@ -334,7 +334,7 @@ func (client *Client) SetAccountSettings(settings AccountSettings) { becameAlwaysOn = (!client.alwaysOn && alwaysOn) client.alwaysOn = alwaysOn if autoreplayMissedDisabled { - client.lastSeen = make(map[string]time.Time) + client.lastSeen = nil } } client.accountSettings = settings From c0f020d87d43ed1cc037038b34c0eea70f077edf Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Sun, 14 Jun 2020 18:54:16 -0400 Subject: [PATCH 007/329] rename oragono.yaml to default.yaml --- oragono.yaml => default.yaml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename oragono.yaml => default.yaml (100%) diff --git a/oragono.yaml b/default.yaml similarity index 100% rename from oragono.yaml rename to default.yaml From a6e2b5a3ae9b7bd5dd7ab0037887401eca66a7be Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Sun, 14 Jun 2020 18:54:36 -0400 Subject: [PATCH 008/329] update references to oragono.yaml to reflect new name of default.yaml --- .goreleaser.yml | 2 +- Dockerfile | 6 +++--- Makefile | 4 ++-- README | 2 +- README.md | 4 ++-- conventional.yaml | 2 +- distrib/docker/run.sh | 2 +- docs/MANUAL.md | 4 ++-- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 391379c4..5a6e6ffd 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -45,7 +45,7 @@ archives: - README - CHANGELOG.md - oragono.motd - - oragono.yaml + - default.yaml - conventional.yaml - docs/* - languages/*.yaml diff --git a/Dockerfile b/Dockerfile index 436a0cbb..91463d8a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,8 +10,8 @@ ADD . /go/src/github.com/oragono/oragono/ # modify default config file so that it doesn't die on IPv6 # and so it can be exposed via 6667 by default -run sed -i 's/^\(\s*\)\"127.0.0.1:6667\":.*$/\1":6667":/' /go/src/github.com/oragono/oragono/oragono.yaml -run sed -i 's/^\s*\"\[::1\]:6667\":.*$//' /go/src/github.com/oragono/oragono/oragono.yaml +run sed -i 's/^\(\s*\)\"127.0.0.1:6667\":.*$/\1":6667":/' /go/src/github.com/oragono/oragono/default.yaml +run sed -i 's/^\s*\"\[::1\]:6667\":.*$//' /go/src/github.com/oragono/oragono/default.yaml # make sure submodules are up-to-date RUN git submodule update --init @@ -40,7 +40,7 @@ EXPOSE 6667/tcp 6697/tcp RUN mkdir -p /ircd-bin COPY --from=build-env /go/bin/oragono /ircd-bin COPY --from=build-env /go/src/github.com/oragono/oragono/languages /ircd-bin/languages/ -COPY --from=build-env /go/src/github.com/oragono/oragono/oragono.yaml /ircd-bin/oragono.yaml +COPY --from=build-env /go/src/github.com/oragono/oragono/default.yaml /ircd-bin/default.yaml COPY distrib/docker/run.sh /ircd-bin/run.sh RUN chmod +x /ircd-bin/run.sh diff --git a/Makefile b/Makefile index 2a5043d7..75ec479e 100644 --- a/Makefile +++ b/Makefile @@ -34,5 +34,5 @@ test: ./.check-gofmt.sh smoke: - oragono mkcerts --conf ./oragono.yaml || true - oragono run --conf ./oragono.yaml --smoke + oragono mkcerts --conf ./default.yaml || true + oragono run --conf ./default.yaml --smoke diff --git a/README b/README index d7db9ca7..e64c8180 100644 --- a/README +++ b/README @@ -23,7 +23,7 @@ assorted IRCv3 support. Copy the example config file to ircd.yaml with a command like: - $ cp oragono.yaml ircd.yaml + $ cp default.yaml ircd.yaml Modify the config file as you like. In particular, the `connection-throttling` and `connection-limits` sections are working looking over and tuning for your network's needs. diff --git a/README.md b/README.md index 544df547..7f89d1f3 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ To go through the standard installation, download the latest release from this p Extract it into a folder, then run the following commands: ```sh -cp oragono.yaml ircd.yaml +cp default.yaml ircd.yaml vim ircd.yaml # modify the config file to your liking oragono mkcerts ``` @@ -84,7 +84,7 @@ You'll need an [up-to-date distribution of the Go language for your OS and archi ## Configuration -The default config file [`oragono.yaml`](oragono.yaml) helps walk you through what each option means and changes. The configuration's intended to be sparse, so if there are options missing it's either because that feature isn't written/configurable yet or because we don't think it should be configurable. +The default config file [`default.yaml`](default.yaml) helps walk you through what each option means and changes. You can use the `--conf` parameter when launching Oragono to control where it looks for the config file. For instance: `oragono run --conf /path/to/ircd.yaml`. The configuration file also stores where the log, database, certificate, and other files are opened. Normally, all these files use relative paths, but you can change them to be absolute (such as `/var/log/ircd.log`) when running Oragono as a service. diff --git a/conventional.yaml b/conventional.yaml index 2cab3fab..0577fc78 100644 --- a/conventional.yaml +++ b/conventional.yaml @@ -18,7 +18,7 @@ server: # This version of the config provides a public plaintext listener on # port 6667 for testing and compatibility with legacy applications. # We recommend disabling this listener in a production setting - # and replacing it with loopback-only listeners (see oragono.yaml): + # and replacing it with loopback-only listeners (see default.yaml): ":6667": # The standard SSL/TLS port for IRC is 6697. This will listen on all interfaces: diff --git a/distrib/docker/run.sh b/distrib/docker/run.sh index f049dd47..fb67aa89 100644 --- a/distrib/docker/run.sh +++ b/distrib/docker/run.sh @@ -5,7 +5,7 @@ cd /ircd # make config file if [ ! -f "/ircd/ircd.yaml" ]; then - awk '{gsub(/path: languages/,"path: /ircd-bin/languages")}1' /ircd-bin/oragono.yaml > /tmp/ircd.yaml + awk '{gsub(/path: languages/,"path: /ircd-bin/languages")}1' /ircd-bin/default.yaml > /tmp/ircd.yaml # change default oper passwd OPERPASS=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c20) diff --git a/docs/MANUAL.md b/docs/MANUAL.md index ea58261e..fce43db5 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -97,7 +97,7 @@ To get started with Oragono on Windows: 1. Make sure you have the [latest release](https://github.com/oragono/oragono/releases/latest) downloaded. 1. Extract the zip file to a folder. -1. Copy and rename `oragono.yaml` to `ircd.yaml`. +1. Copy and rename `default.yaml` to `ircd.yaml`. 1. Open up `ircd.yaml` using any text editor, and then save it once you're happy. 1. Open up a `cmd.exe` window, then `cd` to where you have Oragono extracted. 1. Run `oragono.exe mkcerts` if you want to generate new self-signed SSL/TLS certificates (note that you can't enable STS if you use self-signed certs). @@ -111,7 +111,7 @@ To get started with Oragono on macOS, Linux, or on a Raspberry Pi: 1. Make sure you have the [latest release](https://github.com/oragono/oragono/releases/latest) for your OS/distro downloaded. 1. Extract the tar.gz file to a folder. -1. Copy and rename `oragono.yaml` to `ircd.yaml`. +1. Copy and rename `default.yaml` to `ircd.yaml`. 1. Open up `ircd.yaml` using any text editor, and then save it once you're happy. 1. Open up a Terminal window, then `cd` to where you have Oragono extracted. 1. Run `./oragono mkcerts` if you want to generate new self-signed SSL/TLS certificates (note that you can't enable STS if you use self-signed certs). From 0bbb5d121d5f346ce7e1a335a91e3989e1bf089f Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Wed, 15 Apr 2020 18:14:17 +1000 Subject: [PATCH 009/329] Basic EXTJWT support --- conventional.yaml | 7 +++++ default.yaml | 7 +++++ go.mod | 2 +- go.sum | 2 ++ irc/channel.go | 11 ++++++++ irc/commands.go | 4 +++ irc/config.go | 6 ++-- irc/handlers.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++ irc/help.go | 5 ++++ irc/modes/modes.go | 12 ++++++++ 10 files changed, 121 insertions(+), 3 deletions(-) diff --git a/conventional.yaml b/conventional.yaml index 0577fc78..87215dd6 100644 --- a/conventional.yaml +++ b/conventional.yaml @@ -161,6 +161,13 @@ server: # - "192.168.1.1" # - "192.168.10.1/24" + # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) + # sometimes referred to with 'EXTJWT' + jwt-services: + # # service name -> secret string the service uses to verify our tokens + # call-host: call-hosting-secret-token + # image-host: image-hosting-secret-token + # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks allow-plaintext-resume: false diff --git a/default.yaml b/default.yaml index c5d2aadc..b8fa06ae 100644 --- a/default.yaml +++ b/default.yaml @@ -187,6 +187,13 @@ server: # - "192.168.1.1" # - "192.168.10.1/24" + # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) + # sometimes referred to with 'EXTJWT' + jwt-services: + # # service name -> secret string the service uses to verify our tokens + # call-host: call-hosting-secret-token + # image-host: image-hosting-secret-token + # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks allow-plaintext-resume: false diff --git a/go.mod b/go.mod index 67a5537a..e32c09c0 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,11 @@ go 1.14 require ( code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48 + github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 github.com/go-ldap/ldap/v3 v3.1.10 github.com/go-sql-driver/mysql v1.5.0 github.com/gorilla/websocket v1.4.2 - github.com/goshuirc/e-nfa v0.0.0-20160917075329-7071788e3940 // indirect github.com/goshuirc/irc-go v0.0.0-20200311142257-57fd157327ac github.com/onsi/ginkgo v1.12.0 // indirect github.com/onsi/gomega v1.9.0 // indirect diff --git a/go.sum b/go.sum index 9358a88c..a7f8428d 100644 --- a/go.sum +++ b/go.sum @@ -5,6 +5,8 @@ code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48/go.mod h1:wN/zk github.com/DanielOaks/go-idn v0.0.0-20160120021903-76db0e10dc65/go.mod h1:GYIaL2hleNQvfMUBTes1Zd/lDTyI/p2hv3kYB4jssyU= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 h1:bWDMxwH3px2JBh6AyO7hdCn/PkvCZXii8TGj7sbtEbQ= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= diff --git a/irc/channel.go b/irc/channel.go index 1692eb40..8693e037 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -539,6 +539,17 @@ func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) strin } } +func (channel *Channel) ClientModeStrings(client *Client) []string { + channel.stateMutex.RLock() + defer channel.stateMutex.RUnlock() + modes, present := channel.members[client] + if !present { + return []string{} + } else { + return modes.Strings() + } +} + func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool { channel.stateMutex.RLock() founder := channel.registeredFounder diff --git a/irc/commands.go b/irc/commands.go index aff2d57a..01423c65 100644 --- a/irc/commands.go +++ b/irc/commands.go @@ -130,6 +130,10 @@ func init() { minParams: 1, oper: true, }, + "EXTJWT": { + handler: extjwtHandler, + minParams: 1, + }, "HELP": { handler: helpHandler, minParams: 0, diff --git a/irc/config.go b/irc/config.go index c9db3f0b..0e4e906e 100644 --- a/irc/config.go +++ b/irc/config.go @@ -502,8 +502,9 @@ type Config struct { MOTDFormatting bool `yaml:"motd-formatting"` ProxyAllowedFrom []string `yaml:"proxy-allowed-from"` proxyAllowedFromNets []net.IPNet - WebIRC []webircConfig `yaml:"webirc"` - MaxSendQString string `yaml:"max-sendq"` + WebIRC []webircConfig `yaml:"webirc"` + JwtServices map[string]string `yaml:"jwt-services"` + MaxSendQString string `yaml:"max-sendq"` MaxSendQBytes int AllowPlaintextResume bool `yaml:"allow-plaintext-resume"` Compatibility struct { @@ -1177,6 +1178,7 @@ func (config *Config) generateISupport() (err error) { isupport.Add("CHANTYPES", chanTypes) isupport.Add("ELIST", "U") isupport.Add("EXCEPTS", "") + isupport.Add("EXTJWT", "1") isupport.Add("INVEX", "") isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen)) isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes))) diff --git a/irc/handlers.go b/irc/handlers.go index f1639b7f..df7b1215 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -20,6 +20,7 @@ import ( "strings" "time" + "github.com/dgrijalva/jwt-go" "github.com/goshuirc/irc-go/ircfmt" "github.com/goshuirc/irc-go/ircmsg" "github.com/oragono/oragono/irc/caps" @@ -911,6 +912,73 @@ func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Res return killClient } +// EXTJWT [service_name] +func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool { + expireInSeconds := int64(30) + + accountName := client.AccountName() + if accountName == "*" { + accountName = "" + } + + claims := jwt.MapClaims{ + "exp": time.Now().Unix() + expireInSeconds, + "iss": server.name, + "sub": client.Nick(), + "account": accountName, + "umodes": []string{}, + } + + if msg.Params[0] != "*" { + channel := server.channels.Get(msg.Params[0]) + if channel == nil { + rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_CHANNEL", client.t("No such channel")) + return false + } + + claims["channel"] = channel.Name() + claims["joined"] = 0 + claims["cmodes"] = []string{} + if channel.hasClient(client) { + claims["joined"] = time.Now().Unix() - 100 //TODO(dan): um we need to store when clients joined for reals + claims["cmodes"] = channel.ClientModeStrings(client) + } + } + + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + + // we default to a secret of `*`. if you want a real secret setup a service in the config~ + service := "*" + secret := "*" + if 1 < len(msg.Params) { + service = strings.ToLower(msg.Params[1]) + + c := server.Config() + var exists bool + secret, exists = c.Server.JwtServices[service] + if !exists { + rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service")) + return false + } + } + + tokenString, err := token.SignedString([]byte(secret)) + + if err == nil { + maxTokenLength := 400 + + for maxTokenLength < len(tokenString) { + rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, "*", tokenString[:maxTokenLength]) + tokenString = tokenString[maxTokenLength:] + } + rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, tokenString) + } else { + rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Could not generate EXTJWT token")) + } + + return false +} + // HELP [] func helpHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool { argument := strings.ToLower(strings.TrimSpace(strings.Join(msg.Params, " "))) diff --git a/irc/help.go b/irc/help.go index 4dbd2c82..18ebf3e0 100644 --- a/irc/help.go +++ b/irc/help.go @@ -198,6 +198,11 @@ ON specifies that the ban is to be set on that specific server. [reason] and [oper reason], if they exist, are separated by a vertical bar (|). If "DLINE LIST" is sent, the server sends back a list of our current DLINEs.`, + }, + "extjwt": { + text: `EXTJWT [service_name] + +Get a JSON Web Token for target (either * or a channel name).`, }, "help": { text: `HELP diff --git a/irc/modes/modes.go b/irc/modes/modes.go index ae2d9224..89216cf8 100644 --- a/irc/modes/modes.go +++ b/irc/modes/modes.go @@ -388,6 +388,18 @@ func (set *ModeSet) String() (result string) { return buf.String() } +// Strings returns the modes in this set. +func (set *ModeSet) Strings() (result []string) { + if set == nil { + return + } + + for _, mode := range set.AllModes() { + result = append(result, mode.String()) + } + return +} + // Prefixes returns a list of prefixes for the given set of channel modes. func (set *ModeSet) Prefixes(isMultiPrefix bool) (prefixes string) { if set == nil { From 9b998a7582be4ba586fcebb6b317b80d5e5dd6a7 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Wed, 15 Apr 2020 20:09:51 +1000 Subject: [PATCH 010/329] Allow custom JWT service expiry times --- conventional.yaml | 10 +++++++--- default.yaml | 10 +++++++--- irc/config.go | 18 +++++++++++++++--- irc/handlers.go | 12 +++++++----- 4 files changed, 36 insertions(+), 14 deletions(-) diff --git a/conventional.yaml b/conventional.yaml index 87215dd6..d27ac698 100644 --- a/conventional.yaml +++ b/conventional.yaml @@ -164,9 +164,13 @@ server: # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) # sometimes referred to with 'EXTJWT' jwt-services: - # # service name -> secret string the service uses to verify our tokens - # call-host: call-hosting-secret-token - # image-host: image-hosting-secret-token + # # service name + # call-host: + # # custom expiry length, default is 30s + # expiry-in-seconds: 45 + + # # secret string to verify the generated tokens + # secret: call-hosting-secret-token # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks diff --git a/default.yaml b/default.yaml index b8fa06ae..611be84b 100644 --- a/default.yaml +++ b/default.yaml @@ -190,9 +190,13 @@ server: # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) # sometimes referred to with 'EXTJWT' jwt-services: - # # service name -> secret string the service uses to verify our tokens - # call-host: call-hosting-secret-token - # image-host: image-hosting-secret-token + # # service name + # call-host: + # # custom expiry length, default is 30s + # expiry-in-seconds: 45 + + # # secret string to verify the generated tokens + # secret: call-hosting-secret-token # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks diff --git a/irc/config.go b/irc/config.go index 0e4e906e..cc81792f 100644 --- a/irc/config.go +++ b/irc/config.go @@ -471,6 +471,11 @@ type TorListenersConfig struct { MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"` } +type JwtServiceConfig struct { + ExpiryInSeconds int64 `yaml:"expiry-in-seconds"` + Secret string +} + // Config defines the overall configuration. type Config struct { Network struct { @@ -502,9 +507,9 @@ type Config struct { MOTDFormatting bool `yaml:"motd-formatting"` ProxyAllowedFrom []string `yaml:"proxy-allowed-from"` proxyAllowedFromNets []net.IPNet - WebIRC []webircConfig `yaml:"webirc"` - JwtServices map[string]string `yaml:"jwt-services"` - MaxSendQString string `yaml:"max-sendq"` + WebIRC []webircConfig `yaml:"webirc"` + JwtServices map[string]JwtServiceConfig `yaml:"jwt-services"` + MaxSendQString string `yaml:"max-sendq"` MaxSendQBytes int AllowPlaintextResume bool `yaml:"allow-plaintext-resume"` Compatibility struct { @@ -922,6 +927,13 @@ func LoadConfig(filename string) (config *Config, err error) { config.Server.capValues[caps.Multiline] = multilineCapValue } + // confirm jwt config + for name, info := range config.Server.JwtServices { + if info.Secret == "" { + return nil, fmt.Errorf("Could not parse jwt-services config, %s service has no secret set", name) + } + } + // handle legacy name 'bouncer' for 'multiclient' section: if config.Accounts.Bouncer != nil { config.Accounts.Multiclient = *config.Accounts.Bouncer diff --git a/irc/handlers.go b/irc/handlers.go index df7b1215..880f6d5f 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -922,7 +922,6 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re } claims := jwt.MapClaims{ - "exp": time.Now().Unix() + expireInSeconds, "iss": server.name, "sub": client.Nick(), "account": accountName, @@ -945,8 +944,6 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re } } - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - // we default to a secret of `*`. if you want a real secret setup a service in the config~ service := "*" secret := "*" @@ -954,14 +951,19 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re service = strings.ToLower(msg.Params[1]) c := server.Config() - var exists bool - secret, exists = c.Server.JwtServices[service] + info, exists := c.Server.JwtServices[service] if !exists { rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service")) return false } + secret = info.Secret + if info.ExpiryInSeconds != 0 { + expireInSeconds = info.ExpiryInSeconds + } } + claims["exp"] = time.Now().Unix() + expireInSeconds + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString([]byte(secret)) if err == nil { From 4164c643e65434b2672617634264293969de8a76 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Wed, 15 Apr 2020 21:51:33 +1000 Subject: [PATCH 011/329] Remember when client joins channels, expose in EXTJWT --- irc/channel.go | 24 +++++++++++++++++++----- irc/handlers.go | 8 +++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/irc/channel.go b/irc/channel.go index 8693e037..b9af37fe 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -30,6 +30,7 @@ type Channel struct { key string members MemberSet membersCache []*Client // allow iteration over channel members without holding the lock + memberJoinTimes map[*Client]time.Time name string nameCasefolded string server *Server @@ -57,11 +58,12 @@ func NewChannel(s *Server, name, casefoldedName string, registered bool) *Channe config := s.Config() channel := &Channel{ - createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo - members: make(MemberSet), - name: name, - nameCasefolded: casefoldedName, - server: s, + createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo + members: make(MemberSet), + memberJoinTimes: make(map[*Client]time.Time), + name: name, + nameCasefolded: casefoldedName, + server: s, } channel.initializeLists() @@ -550,6 +552,16 @@ func (channel *Channel) ClientModeStrings(client *Client) []string { } } +func (channel *Channel) ClientJoinTime(client *Client) *time.Time { + channel.stateMutex.RLock() + defer channel.stateMutex.RUnlock() + time, present := channel.memberJoinTimes[client] + if present { + return &time + } + return nil +} + func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool { channel.stateMutex.RLock() founder := channel.registeredFounder @@ -726,6 +738,7 @@ func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *Resp defer channel.stateMutex.Unlock() channel.members.Add(client) + channel.memberJoinTimes[client] = time.Now() firstJoin := len(channel.members) == 1 newChannel := firstJoin && channel.registeredFounder == "" if newChannel { @@ -1364,6 +1377,7 @@ func (channel *Channel) Quit(client *Client) { channel.stateMutex.Lock() channel.members.Remove(client) + delete(channel.memberJoinTimes, client) channelEmpty := len(channel.members) == 0 channel.stateMutex.Unlock() channel.regenerateMembersCache() diff --git a/irc/handlers.go b/irc/handlers.go index 880f6d5f..d6deaa35 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -939,7 +939,13 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re claims["joined"] = 0 claims["cmodes"] = []string{} if channel.hasClient(client) { - claims["joined"] = time.Now().Unix() - 100 //TODO(dan): um we need to store when clients joined for reals + joinTime := channel.ClientJoinTime(client) + if joinTime == nil { + // shouldn't happen, only in races + rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Channel join time is inconsistent, JWT not generated")) + return false + } + claims["joined"] = joinTime.Unix() claims["cmodes"] = channel.ClientModeStrings(client) } } From 6bee1f6d6a17a0d2f8cf04a5be05984bff46706b Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Fri, 17 Apr 2020 16:23:18 +1000 Subject: [PATCH 012/329] Review fixes --- irc/channel.go | 22 ++++++++++------------ irc/handlers.go | 2 +- irc/modes/modes.go | 12 ------------ 3 files changed, 11 insertions(+), 25 deletions(-) diff --git a/irc/channel.go b/irc/channel.go index b9af37fe..3b47b49d 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -541,25 +541,23 @@ func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) strin } } -func (channel *Channel) ClientModeStrings(client *Client) []string { +func (channel *Channel) ClientModeStrings(client *Client) (result []string) { channel.stateMutex.RLock() defer channel.stateMutex.RUnlock() modes, present := channel.members[client] - if !present { - return []string{} - } else { - return modes.Strings() + if present { + for _, mode := range modes.AllModes() { + result = append(result, mode.String()) + } } + return } -func (channel *Channel) ClientJoinTime(client *Client) *time.Time { +func (channel *Channel) ClientJoinTime(client *Client) time.Time { channel.stateMutex.RLock() defer channel.stateMutex.RUnlock() - time, present := channel.memberJoinTimes[client] - if present { - return &time - } - return nil + time := channel.memberJoinTimes[client] + return time } func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool { @@ -738,7 +736,7 @@ func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *Resp defer channel.stateMutex.Unlock() channel.members.Add(client) - channel.memberJoinTimes[client] = time.Now() + channel.memberJoinTimes[client] = time.Now().UTC() firstJoin := len(channel.members) == 1 newChannel := firstJoin && channel.registeredFounder == "" if newChannel { diff --git a/irc/handlers.go b/irc/handlers.go index d6deaa35..3daeb358 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -940,7 +940,7 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re claims["cmodes"] = []string{} if channel.hasClient(client) { joinTime := channel.ClientJoinTime(client) - if joinTime == nil { + if joinTime.IsZero() { // shouldn't happen, only in races rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Channel join time is inconsistent, JWT not generated")) return false diff --git a/irc/modes/modes.go b/irc/modes/modes.go index 89216cf8..ae2d9224 100644 --- a/irc/modes/modes.go +++ b/irc/modes/modes.go @@ -388,18 +388,6 @@ func (set *ModeSet) String() (result string) { return buf.String() } -// Strings returns the modes in this set. -func (set *ModeSet) Strings() (result []string) { - if set == nil { - return - } - - for _, mode := range set.AllModes() { - result = append(result, mode.String()) - } - return -} - // Prefixes returns a list of prefixes for the given set of channel modes. func (set *ModeSet) Prefixes(isMultiPrefix bool) (prefixes string) { if set == nil { From 31b6bfa84e6492c790c8b9003bce33201364eb01 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Fri, 12 Jun 2020 17:04:36 -0400 Subject: [PATCH 013/329] readd vendored module changes --- vendor/github.com/dgrijalva/jwt-go/.gitignore | 4 + .../github.com/dgrijalva/jwt-go/.travis.yml | 13 ++ vendor/github.com/dgrijalva/jwt-go/LICENSE | 8 + .../dgrijalva/jwt-go/MIGRATION_GUIDE.md | 97 ++++++++++++ vendor/github.com/dgrijalva/jwt-go/README.md | 100 ++++++++++++ .../dgrijalva/jwt-go/VERSION_HISTORY.md | 118 ++++++++++++++ vendor/github.com/dgrijalva/jwt-go/claims.go | 134 ++++++++++++++++ vendor/github.com/dgrijalva/jwt-go/doc.go | 4 + vendor/github.com/dgrijalva/jwt-go/ecdsa.go | 148 ++++++++++++++++++ .../dgrijalva/jwt-go/ecdsa_utils.go | 67 ++++++++ vendor/github.com/dgrijalva/jwt-go/errors.go | 59 +++++++ vendor/github.com/dgrijalva/jwt-go/hmac.go | 95 +++++++++++ .../github.com/dgrijalva/jwt-go/map_claims.go | 94 +++++++++++ vendor/github.com/dgrijalva/jwt-go/none.go | 52 ++++++ vendor/github.com/dgrijalva/jwt-go/parser.go | 148 ++++++++++++++++++ vendor/github.com/dgrijalva/jwt-go/rsa.go | 101 ++++++++++++ vendor/github.com/dgrijalva/jwt-go/rsa_pss.go | 126 +++++++++++++++ .../github.com/dgrijalva/jwt-go/rsa_utils.go | 101 ++++++++++++ .../dgrijalva/jwt-go/signing_method.go | 35 +++++ vendor/github.com/dgrijalva/jwt-go/token.go | 108 +++++++++++++ vendor/modules.txt | 5 +- 21 files changed, 1615 insertions(+), 2 deletions(-) create mode 100644 vendor/github.com/dgrijalva/jwt-go/.gitignore create mode 100644 vendor/github.com/dgrijalva/jwt-go/.travis.yml create mode 100644 vendor/github.com/dgrijalva/jwt-go/LICENSE create mode 100644 vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md create mode 100644 vendor/github.com/dgrijalva/jwt-go/README.md create mode 100644 vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md create mode 100644 vendor/github.com/dgrijalva/jwt-go/claims.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/doc.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/errors.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/map_claims.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/none.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/parser.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_pss.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_utils.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/signing_method.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/token.go diff --git a/vendor/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/dgrijalva/jwt-go/.gitignore new file mode 100644 index 00000000..80bed650 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +bin + + diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml new file mode 100644 index 00000000..1027f56c --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/.travis.yml @@ -0,0 +1,13 @@ +language: go + +script: + - go vet ./... + - go test -v ./... + +go: + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - 1.7 + - tip diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE new file mode 100644 index 00000000..df83a9c2 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/LICENSE @@ -0,0 +1,8 @@ +Copyright (c) 2012 Dave Grijalva + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md new file mode 100644 index 00000000..7fc1f793 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md @@ -0,0 +1,97 @@ +## Migration Guide from v2 -> v3 + +Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. + +### `Token.Claims` is now an interface type + +The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. + +`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. + +The old example for parsing a token looked like this.. + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is now directly mapped to... + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + claims := token.Claims.(jwt.MapClaims) + fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) + } +``` + +`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. + +```go + type MyCustomClaims struct { + User string + *StandardClaims + } + + if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { + claims := token.Claims.(*MyCustomClaims) + fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) + } +``` + +### `ParseFromRequest` has been moved + +To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. + +`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. + +This simple parsing example: + +```go + if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is directly mapped to: + +```go + if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { + claims := token.Claims.(jwt.MapClaims) + fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) + } +``` + +There are several concrete `Extractor` types provided for your convenience: + +* `HeaderExtractor` will search a list of headers until one contains content. +* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. +* `MultiExtractor` will try a list of `Extractors` in order until one returns content. +* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. +* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument +* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header + + +### RSA signing methods no longer accept `[]byte` keys + +Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. + +To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. + +```go + func keyLookupFunc(*Token) (interface{}, error) { + // Don't forget to validate the alg is what you expect: + if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { + return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + } + + // Look up key + key, err := lookupPublicKey(token.Header["kid"]) + if err != nil { + return nil, err + } + + // Unpack key from PEM encoded PKCS8 + return jwt.ParseRSAPublicKeyFromPEM(key) + } +``` diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md new file mode 100644 index 00000000..d358d881 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/README.md @@ -0,0 +1,100 @@ +# jwt-go + +[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) +[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) + +**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. + +**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. + +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. + +## What the heck is a JWT? + +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. + +In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. + +The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. + +The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own. + +## What's in the box? + +This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. + +## Examples + +See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: + +* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) +* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) +* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) + +## Extensions + +This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. + +Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go + +## Compliance + +This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: + +* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. + +## Project Status & Versioning + +This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). + +This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). + +While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. + +**BREAKING CHANGES:*** +* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. + +## Usage Tips + +### Signing vs Encryption + +A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: + +* The author of the token was in the possession of the signing secret +* The data has not been modified since it was signed + +It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. + +### Choosing a Signing Method + +There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. + +Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. + +Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. + +### Signing Methods and Key Types + +Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: + +* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation + +### JWT and OAuth + +It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. + +Without going too far down the rabbit hole, here's a description of the interaction of these technologies: + +* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. +* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. +* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. + +## More + +Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). + +The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md new file mode 100644 index 00000000..63702983 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md @@ -0,0 +1,118 @@ +## `jwt-go` Version History + +#### 3.2.0 + +* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation +* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate +* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. +* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. + +#### 3.1.0 + +* Improvements to `jwt` command line tool +* Added `SkipClaimsValidation` option to `Parser` +* Documentation updates + +#### 3.0.0 + +* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code + * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. + * `ParseFromRequest` has been moved to `request` subpackage and usage has changed + * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. +* Other Additions and Changes + * Added `Claims` interface type to allow users to decode the claims into a custom type + * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. + * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage + * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` + * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. + * Added several new, more specific, validation errors to error type bitmask + * Moved examples from README to executable example files + * Signing method registry is now thread safe + * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) + +#### 2.7.0 + +This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. + +* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying +* Error text for expired tokens includes how long it's been expired +* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` +* Documentation updates + +#### 2.6.0 + +* Exposed inner error within ValidationError +* Fixed validation errors when using UseJSONNumber flag +* Added several unit tests + +#### 2.5.0 + +* Added support for signing method none. You shouldn't use this. The API tries to make this clear. +* Updated/fixed some documentation +* Added more helpful error message when trying to parse tokens that begin with `BEARER ` + +#### 2.4.0 + +* Added new type, Parser, to allow for configuration of various parsing parameters + * You can now specify a list of valid signing methods. Anything outside this set will be rejected. + * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON +* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) +* Fixed some bugs with ECDSA parsing + +#### 2.3.0 + +* Added support for ECDSA signing methods +* Added support for RSA PSS signing methods (requires go v1.4) + +#### 2.2.0 + +* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. + +#### 2.1.0 + +Backwards compatible API change that was missed in 2.0.0. + +* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` + +#### 2.0.0 + +There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. + +The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. + +It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. + +* **Compatibility Breaking Changes** + * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` + * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` + * `KeyFunc` now returns `interface{}` instead of `[]byte` + * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key + * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key +* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. + * Added public package global `SigningMethodHS256` + * Added public package global `SigningMethodHS384` + * Added public package global `SigningMethodHS512` +* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. + * Added public package global `SigningMethodRS256` + * Added public package global `SigningMethodRS384` + * Added public package global `SigningMethodRS512` +* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. +* Refactored the RSA implementation to be easier to read +* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` + +#### 1.0.2 + +* Fixed bug in parsing public keys from certificates +* Added more tests around the parsing of keys for RS256 +* Code refactoring in RS256 implementation. No functional changes + +#### 1.0.1 + +* Fixed panic if RS256 signing method was passed an invalid key + +#### 1.0.0 + +* First versioned release +* API stabilized +* Supports creating, signing, parsing, and validating JWT tokens +* Supports RS256 and HS256 signing methods \ No newline at end of file diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go new file mode 100644 index 00000000..f0228f02 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/claims.go @@ -0,0 +1,134 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// For a type to be a Claims object, it must just have a Valid method that determines +// if the token is invalid for any supported reason +type Claims interface { + Valid() error +} + +// Structured version of Claims Section, as referenced at +// https://tools.ietf.org/html/rfc7519#section-4.1 +// See examples for how to use this with your own claim types +type StandardClaims struct { + Audience string `json:"aud,omitempty"` + ExpiresAt int64 `json:"exp,omitempty"` + Id string `json:"jti,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + Issuer string `json:"iss,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + Subject string `json:"sub,omitempty"` +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if c.VerifyExpiresAt(now, false) == false { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("token is expired by %v", delta) + vErr.Errors |= ValidationErrorExpired + } + + if c.VerifyIssuedAt(now, false) == false { + vErr.Inner = fmt.Errorf("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if c.VerifyNotBefore(now, false) == false { + vErr.Inner = fmt.Errorf("token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + return verifyExp(c.ExpiresAt, cmp, req) +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + return verifyIat(c.IssuedAt, cmp, req) +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + return verifyNbf(c.NotBefore, cmp, req) +} + +// ----- helpers + +func verifyAud(aud string, cmp string, required bool) bool { + if aud == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyExp(exp int64, now int64, required bool) bool { + if exp == 0 { + return !required + } + return now <= exp +} + +func verifyIat(iat int64, now int64, required bool) bool { + if iat == 0 { + return !required + } + return now >= iat +} + +func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyNbf(nbf int64, now int64, required bool) bool { + if nbf == 0 { + return !required + } + return now >= nbf +} diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go new file mode 100644 index 00000000..a86dc1a3 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/doc.go @@ -0,0 +1,4 @@ +// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html +// +// See README.md for more info. +package jwt diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go new file mode 100644 index 00000000..f9773812 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rand" + "errors" + "math/big" +) + +var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") +) + +// Implements the ECDSA family of signing methods signing methods +// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification +type SigningMethodECDSA struct { + Name string + Hash crypto.Hash + KeySize int + CurveBits int +} + +// Specific instances for EC256 and company +var ( + SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA +) + +func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) + + // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) + + // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) +} + +func (m *SigningMethodECDSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an ecdsa.PublicKey struct +func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } + + if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } + + r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { + return nil + } else { + return ErrECDSAVerification + } +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an ecdsa.PrivateKey struct +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize + + if m.CurveBits != curveBits { + return "", ErrInvalidKey + } + + keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } + + // We serialize the outpus (r and s) into big-endian byte arrays and pad + // them with zeros on the left to make sure the sizes work out. Both arrays + // must be keyBytes long, and the output must be 2*keyBytes long. + rBytes := r.Bytes() + rBytesPadded := make([]byte, keyBytes) + copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) + + sBytes := s.Bytes() + sBytesPadded := make([]byte, keyBytes) + copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) + + out := append(rBytesPadded, sBytesPadded...) + + return EncodeSegment(out), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go new file mode 100644 index 00000000..d19624b7 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go @@ -0,0 +1,67 @@ +package jwt + +import ( + "crypto/ecdsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") +) + +// Parse PEM encoded Elliptic Curve Private Key Structure +func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + return nil, err + } + + var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go new file mode 100644 index 00000000..1c93024a --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/errors.go @@ -0,0 +1,59 @@ +package jwt + +import ( + "errors" +) + +// Error constants +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") +) + +// The errors that might occur when parsing and validating a token +const ( + ValidationErrorMalformed uint32 = 1 << iota // Token is malformed + ValidationErrorUnverifiable // Token could not be verified because of signing problems + ValidationErrorSignatureInvalid // Signature validation failed + + // Standard Claim validation errors + ValidationErrorAudience // AUD validation failed + ValidationErrorExpired // EXP validation failed + ValidationErrorIssuedAt // IAT validation failed + ValidationErrorIssuer // ISS validation failed + ValidationErrorNotValidYet // NBF validation failed + ValidationErrorId // JTI validation failed + ValidationErrorClaimsInvalid // Generic claims validation error +) + +// Helper for constructing a ValidationError with a string error message +func NewValidationError(errorText string, errorFlags uint32) *ValidationError { + return &ValidationError{ + text: errorText, + Errors: errorFlags, + } +} + +// The error from Parse if token is not valid +type ValidationError struct { + Inner error // stores the error returned by external dependencies, i.e.: KeyFunc + Errors uint32 // bitfield. see ValidationError... constants + text string // errors that do not have a valid error just have text +} + +// Validation error is an error type +func (e ValidationError) Error() string { + if e.Inner != nil { + return e.Inner.Error() + } else if e.text != "" { + return e.text + } else { + return "token is invalid" + } +} + +// No errors +func (e *ValidationError) valid() bool { + return e.Errors == 0 +} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go new file mode 100644 index 00000000..addbe5d4 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go @@ -0,0 +1,95 @@ +package jwt + +import ( + "crypto" + "crypto/hmac" + "errors" +) + +// Implements the HMAC-SHA family of signing methods signing methods +// Expects key type of []byte for both signing and validation +type SigningMethodHMAC struct { + Name string + Hash crypto.Hash +} + +// Specific instances for HS256 and company +var ( + SigningMethodHS256 *SigningMethodHMAC + SigningMethodHS384 *SigningMethodHMAC + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") +) + +func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) + + // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) + + // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) +} + +func (m *SigningMethodHMAC) Alg() string { + return m.Name +} + +// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. +func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } + + // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { + return err + } + + // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } + + // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } + + // No validation errors. Signature is good. + return nil +} + +// Implements the Sign method from SigningMethod for this signing method. +// Key must be []byte +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + + return EncodeSegment(hasher.Sum(nil)), nil + } + + return "", ErrInvalidKeyType +} diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go new file mode 100644 index 00000000..291213c4 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/map_claims.go @@ -0,0 +1,94 @@ +package jwt + +import ( + "encoding/json" + "errors" + // "fmt" +) + +// Claims type that uses the map[string]interface{} for JSON decoding +// This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + aud, _ := m["aud"].(string) + return verifyAud(aud, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + switch exp := m["exp"].(type) { + case float64: + return verifyExp(int64(exp), cmp, req) + case json.Number: + v, _ := exp.Int64() + return verifyExp(v, cmp, req) + } + return req == false +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + switch iat := m["iat"].(type) { + case float64: + return verifyIat(int64(iat), cmp, req) + case json.Number: + v, _ := iat.Int64() + return verifyIat(v, cmp, req) + } + return req == false +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + switch nbf := m["nbf"].(type) { + case float64: + return verifyNbf(int64(nbf), cmp, req) + case json.Number: + v, _ := nbf.Int64() + return verifyNbf(v, cmp, req) + } + return req == false +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + if m.VerifyExpiresAt(now, false) == false { + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } + + if m.VerifyIssuedAt(now, false) == false { + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if m.VerifyNotBefore(now, false) == false { + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go new file mode 100644 index 00000000..f04d189d --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/none.go @@ -0,0 +1,52 @@ +package jwt + +// Implements the none signing method. This is required by the spec +// but you probably should never use it. +var SigningMethodNone *signingMethodNone + +const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" + +var NoneSignatureTypeDisallowedError error + +type signingMethodNone struct{} +type unsafeNoneMagicConstant string + +func init() { + SigningMethodNone = &signingMethodNone{} + NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + + RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { + return SigningMethodNone + }) +} + +func (m *signingMethodNone) Alg() string { + return "none" +} + +// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { + // Key must be UnsafeAllowNoneSignatureType to prevent accidentally + // accepting 'none' signing method + if _, ok := key.(unsafeNoneMagicConstant); !ok { + return NoneSignatureTypeDisallowedError + } + // If signing method is none, signature must be an empty string + if signature != "" { + return NewValidationError( + "'none' signing method with non-empty signature", + ValidationErrorSignatureInvalid, + ) + } + + // Accept 'none' signing method. + return nil +} + +// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { + if _, ok := key.(unsafeNoneMagicConstant); ok { + return "", nil + } + return "", NoneSignatureTypeDisallowedError +} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go new file mode 100644 index 00000000..d6901d9a --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + ValidMethods []string // If populated, only these methods will be considered valid + UseJSONNumber bool // Use JSON Number format in JSON decoder + SkipClaimsValidation bool // Skip claims validation during token parsing +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } + + // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } + + // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } + + vErr := &ValidationError{} + + // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { + + // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } + + // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } + + if vErr.valid() { + token.Valid = true + return token, nil + } + + return token, vErr +} + +// WARNING: Don't use this method unless you know what you're doing +// +// This method parses the token but doesn't validate the signature. It's only +// ever useful in cases where you know the signature is valid (because it has +// been checked previously in the stack) and you want to extract values from +// it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // parse Claims + var claimBytes []byte + token.Claims = claims + + if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } + + return token, parts, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go new file mode 100644 index 00000000..e4caf1ca --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSA family of signing methods signing methods +// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation +type SigningMethodRSA struct { + Name string + Hash crypto.Hash +} + +// Specific instances for RS256 and company +var ( + SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA +) + +func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) + + // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) + + // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) +} + +func (m *SigningMethodRSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this signing method, must be an *rsa.PublicKey structure. +func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + var ok bool + + if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) +} + +// Implements the Sign method from SigningMethod +// For this signing method, must be an *rsa.PrivateKey structure. +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + var ok bool + + // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return "", ErrInvalidKey + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go new file mode 100644 index 00000000..10ee9db8 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go @@ -0,0 +1,126 @@ +// +build go1.4 + +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSAPSS family of signing methods signing methods +type SigningMethodRSAPSS struct { + *SigningMethodRSA + Options *rsa.PSSOptions +} + +// Specific instances for RS/PS and company +var ( + SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS +) + +func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA256, + }, + } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) + + // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA384, + }, + } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) + + // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA512, + }, + } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an rsa.PublicKey struct +func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an rsa.PrivateKey struct +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + + switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go new file mode 100644 index 00000000..a5ababf9 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") + ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") + ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") +) + +// Parse PEM encoded PKCS1 or PKCS8 private key +func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 private key protected with password +func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + + var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } + + if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go new file mode 100644 index 00000000..ed1f212b --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/signing_method.go @@ -0,0 +1,35 @@ +package jwt + +import ( + "sync" +) + +var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) + +// Implement SigningMethod to add new methods for signing or verifying tokens. +type SigningMethod interface { + Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') +} + +// Register the "alg" name and a factory function for signing method. +// This is typically done during init() in the method's implementation +func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + + signingMethods[alg] = f +} + +// Get a signing method from an "alg" string +func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + if methodF, ok := signingMethods[alg]; ok { + method = methodF() + } + return +} diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go new file mode 100644 index 00000000..d637e086 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/token.go @@ -0,0 +1,108 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" + "time" +) + +// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). +// You can override it to use another time value. This is useful for testing or if your +// server uses a different time zone than your tokens. +var TimeFunc = time.Now + +// Parse methods use this callback function to supply +// the key for verification. The function receives the parsed, +// but unverified Token. This allows you to use properties in the +// Header of the token (such as `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// A JWT Token. Different fields will be used depending on whether you're +// creating or parsing/verifying a token. +type Token struct { + Raw string // The raw token. Populated when you Parse a token + Method SigningMethod // The signing method used or to be used + Header map[string]interface{} // The first segment of the token + Claims Claims // The second segment of the token + Signature string // The third segment of the token. Populated when you Parse a token + Valid bool // Is the token valid? Populated when you Parse/Verify a token +} + +// Create a new Token. Takes a signing method +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// Get the complete, signed token +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// Generate the signing string. This is the +// most expensive part of the whole deal. Unless you +// need this for something special, just go straight for +// the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + parts := make([]string, 2) + for i, _ := range parts { + var jsonValue []byte + if i == 0 { + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + } else { + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + } + + parts[i] = EncodeSegment(jsonValue) + } + return strings.Join(parts, "."), nil +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return new(Parser).Parse(tokenString, keyFunc) +} + +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) +} + +// Encode JWT specific base64url encoding with padding stripped +func EncodeSegment(seg []byte) string { + return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") +} + +// Decode JWT specific base64url encoding with padding stripped +func DecodeSegment(seg string) ([]byte, error) { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + + return base64.URLEncoding.DecodeString(seg) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index ce206d7e..00b04b31 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,9 @@ # code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48 ## explicit code.cloudfoundry.org/bytefmt +# github.com/dgrijalva/jwt-go v3.2.0+incompatible +## explicit +github.com/dgrijalva/jwt-go # github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 ## explicit github.com/docopt/docopt-go @@ -15,8 +18,6 @@ github.com/go-sql-driver/mysql # github.com/gorilla/websocket v1.4.2 ## explicit github.com/gorilla/websocket -# github.com/goshuirc/e-nfa v0.0.0-20160917075329-7071788e3940 -## explicit # github.com/goshuirc/irc-go v0.0.0-20200311142257-57fd157327ac ## explicit github.com/goshuirc/irc-go/ircfmt From 18fd86ce98e5a850d4545e2d974f0342f78ae79b Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Fri, 12 Jun 2020 17:11:19 -0400 Subject: [PATCH 014/329] run `go mod tidy` --- go.mod | 1 + go.sum | 29 ++--------------------------- vendor/modules.txt | 2 ++ 3 files changed, 5 insertions(+), 27 deletions(-) diff --git a/go.mod b/go.mod index e32c09c0..3d76a304 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 github.com/go-ldap/ldap/v3 v3.1.10 github.com/go-sql-driver/mysql v1.5.0 + github.com/go-test/deep v1.0.6 // indirect github.com/gorilla/websocket v1.4.2 github.com/goshuirc/irc-go v0.0.0-20200311142257-57fd157327ac github.com/onsi/ginkgo v1.12.0 // indirect diff --git a/go.sum b/go.sum index a7f8428d..3e5dfa3c 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,3 @@ -code.cloudfoundry.org/bytefmt v0.0.0-20190819182555-854d396b647c h1:2RuXx1+tSNWRjxhY0Bx52kjV2odJQ0a6MTbfTPhGAkg= -code.cloudfoundry.org/bytefmt v0.0.0-20190819182555-854d396b647c/go.mod h1:wN/zk7mhREp/oviagqUXY3EwuHhWyOvAdsn5Y4CzOrc= code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48 h1:/EMHruHCFXR9xClkGV/t0rmHrdhX4+trQUcBqjwc9xE= code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48/go.mod h1:wN/zk7mhREp/oviagqUXY3EwuHhWyOvAdsn5Y4CzOrc= github.com/DanielOaks/go-idn v0.0.0-20160120021903-76db0e10dc65/go.mod h1:GYIaL2hleNQvfMUBTes1Zd/lDTyI/p2hv3kYB4jssyU= @@ -13,33 +11,22 @@ github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/go-asn1-ber/asn1-ber v1.3.1 h1:gvPdv/Hr++TRFCl0UbPFHC54P9N9jgsRPnmnr419Uck= github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= -github.com/go-ldap/ldap/v3 v3.1.6 h1:VTihvB7egSAvU6KOagaiA/EvgJMR2jsjRAVIho2ydBo= -github.com/go-ldap/ldap/v3 v3.1.6/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q= -github.com/go-ldap/ldap/v3 v3.1.7 h1:aHjuWTgZsnxjMgqzx0JHwNqz4jBYZTcNarbPFkW1Oww= -github.com/go-ldap/ldap/v3 v3.1.7/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q= github.com/go-ldap/ldap/v3 v3.1.10 h1:7WsKqasmPThNvdl0Q5GPpbTDD/ZD98CfuawrMIuh7qQ= github.com/go-ldap/ldap/v3 v3.1.10/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-test/deep v1.0.6 h1:UHSEyLZUwX9Qoi99vVwvewiMC8mM2bf7XEM2nqvzEn8= +github.com/go-test/deep v1.0.6/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V36o8= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/goshuirc/e-nfa v0.0.0-20160917075329-7071788e3940 h1:KmRLPRstEJiE/9OjumKqI8Rccip8Qmyw2FwyTFxtVqs= github.com/goshuirc/e-nfa v0.0.0-20160917075329-7071788e3940/go.mod h1:VOmrX6cmj7zwUeexC9HzznUdTIObHqIXUrWNYS+Ik7w= -github.com/goshuirc/irc-go v0.0.0-20190713001546-05ecc95249a0 h1:unxsR0de0MIS708eZI7lKa6HiP8FS0PhGCWwwEt9+vQ= -github.com/goshuirc/irc-go v0.0.0-20190713001546-05ecc95249a0/go.mod h1:rhIkxdehxNqK9iwJXWzQnxlGuuUR4cHu7PN64VryKXk= github.com/goshuirc/irc-go v0.0.0-20200311142257-57fd157327ac h1:0JSojWrghcpK9/wx1RpV9Bv2d+3TbBWtHWubKjU2tao= github.com/goshuirc/irc-go v0.0.0-20200311142257-57fd157327ac/go.mod h1:BRnLblzpqH2T5ANCODHBZLytz0NZN2KaMJ+di8oh3EM= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= -github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= -github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= -github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= @@ -48,8 +35,6 @@ github.com/onsi/gomega v1.9.0 h1:R1uwffexN6Pr340GtYRIdZmAiN4J+iw6WG4wog1DUXg= github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= github.com/oragono/confusables v0.0.0-20190624102032-fe1cf31a24b0 h1:4qw57EiWD2MhnmXoQus2ClSyPpGRd8/UxcAmmNe2FCg= github.com/oragono/confusables v0.0.0-20190624102032-fe1cf31a24b0/go.mod h1:+uesPRay9e5tW6zhw4CJkRV3QOEbbZIJcsuo9ZnC+hE= -github.com/oragono/go-ident v0.0.0-20170110123031-337fed0fd21a h1:tZApUffT5QuX4XhJLz2KfBJT8JgdwjLUBWtvmRwgFu4= -github.com/oragono/go-ident v0.0.0-20170110123031-337fed0fd21a/go.mod h1:r5Fk840a4eu3ii1kxGDNSJupQu9Z1UC1nfJOZZXC24c= github.com/oragono/go-ident v0.0.0-20200511222032-830550b1d775 h1:AMAsAn/i4AgsmWQYdMoze9omwtHpbxrKuT+AT1LmhtI= github.com/oragono/go-ident v0.0.0-20200511222032-830550b1d775/go.mod h1:r5Fk840a4eu3ii1kxGDNSJupQu9Z1UC1nfJOZZXC24c= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -73,13 +58,9 @@ github.com/tidwall/rtree v0.0.0-20180113144539-6cd427091e0e h1:+NL1GDIUOKxVfbp2K github.com/tidwall/rtree v0.0.0-20180113144539-6cd427091e0e/go.mod h1:/h+UnNGt0IhNNJLkGikcdcJqm66zGD/uJGMRxK/9+Ao= github.com/tidwall/tinyqueue v0.0.0-20180302190814-1e39f5511563 h1:Otn9S136ELckZ3KKDyCkxapfufrqDqwmGjcHfAyXRrE= github.com/tidwall/tinyqueue v0.0.0-20180302190814-1e39f5511563/go.mod h1:mLqSmt7Dv/CNneF2wfcChfN1rvapyQr01LGKnKex0DQ= -github.com/toorop/go-dkim v0.0.0-20191019073156-897ad64a2eeb h1:ilDZC+k9r67aJqSOalZLtEVLO7Cmmsq5ftfcvLirc24= -github.com/toorop/go-dkim v0.0.0-20191019073156-897ad64a2eeb/go.mod h1:BzWtXXrXzZUvMacR0oF/fbDDgUPO8L36tDMmRAf14ns= github.com/toorop/go-dkim v0.0.0-20200526084421-76378ae5207e h1:uZTp+hhFm+PCH0t0Px5oE+QYlVTwVJ+XKNQr7ct4Q7w= github.com/toorop/go-dkim v0.0.0-20200526084421-76378ae5207e/go.mod h1:BzWtXXrXzZUvMacR0oF/fbDDgUPO8L36tDMmRAf14ns= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708 h1:pXVtWnwHkrWD9ru3sDxY/qFK/bfc0egRovX91EjWjf4= -golang.org/x/crypto v0.0.0-20191112222119-e1110fd1c708/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 h1:xMPOj6Pz6UipU1wXLkrtqpHbR0AVFnyPEQq/wRWz9lM= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -89,9 +70,7 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6Zh golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e h1:N7DeIrjYszNmSW409R3frPPwglRwMkXSBzwVbkOjLLA= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o= @@ -110,9 +89,5 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkep gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5 h1:ymVxjfMaHvXD8RqPRmzHHsB3VvucivSkIAvJFDI5O3c= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/modules.txt b/vendor/modules.txt index 00b04b31..2ad3556c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -15,6 +15,8 @@ github.com/go-ldap/ldap/v3 # github.com/go-sql-driver/mysql v1.5.0 ## explicit github.com/go-sql-driver/mysql +# github.com/go-test/deep v1.0.6 +## explicit # github.com/gorilla/websocket v1.4.2 ## explicit github.com/gorilla/websocket From bfeba1f2f30daf22c3405d4147b09f255b5dc39b Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Fri, 12 Jun 2020 17:13:47 -0400 Subject: [PATCH 015/329] remove client join time tracking --- irc/channel.go | 21 +++++---------------- irc/handlers.go | 8 +------- 2 files changed, 6 insertions(+), 23 deletions(-) diff --git a/irc/channel.go b/irc/channel.go index 3b47b49d..842ddc39 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -30,7 +30,6 @@ type Channel struct { key string members MemberSet membersCache []*Client // allow iteration over channel members without holding the lock - memberJoinTimes map[*Client]time.Time name string nameCasefolded string server *Server @@ -58,12 +57,11 @@ func NewChannel(s *Server, name, casefoldedName string, registered bool) *Channe config := s.Config() channel := &Channel{ - createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo - members: make(MemberSet), - memberJoinTimes: make(map[*Client]time.Time), - name: name, - nameCasefolded: casefoldedName, - server: s, + createdTime: time.Now().UTC(), // may be overwritten by applyRegInfo + members: make(MemberSet), + name: name, + nameCasefolded: casefoldedName, + server: s, } channel.initializeLists() @@ -553,13 +551,6 @@ func (channel *Channel) ClientModeStrings(client *Client) (result []string) { return } -func (channel *Channel) ClientJoinTime(client *Client) time.Time { - channel.stateMutex.RLock() - defer channel.stateMutex.RUnlock() - time := channel.memberJoinTimes[client] - return time -} - func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool { channel.stateMutex.RLock() founder := channel.registeredFounder @@ -736,7 +727,6 @@ func (channel *Channel) Join(client *Client, key string, isSajoin bool, rb *Resp defer channel.stateMutex.Unlock() channel.members.Add(client) - channel.memberJoinTimes[client] = time.Now().UTC() firstJoin := len(channel.members) == 1 newChannel := firstJoin && channel.registeredFounder == "" if newChannel { @@ -1375,7 +1365,6 @@ func (channel *Channel) Quit(client *Client) { channel.stateMutex.Lock() channel.members.Remove(client) - delete(channel.memberJoinTimes, client) channelEmpty := len(channel.members) == 0 channel.stateMutex.Unlock() channel.regenerateMembersCache() diff --git a/irc/handlers.go b/irc/handlers.go index 3daeb358..c0decf2d 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -939,13 +939,7 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re claims["joined"] = 0 claims["cmodes"] = []string{} if channel.hasClient(client) { - joinTime := channel.ClientJoinTime(client) - if joinTime.IsZero() { - // shouldn't happen, only in races - rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Channel join time is inconsistent, JWT not generated")) - return false - } - claims["joined"] = joinTime.Unix() + claims["joined"] = 1 claims["cmodes"] = channel.ClientModeStrings(client) } } From e61e0143bdf04a642a5034753f1002cfd6acf569 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jun 2020 14:16:02 -0400 Subject: [PATCH 016/329] refactor/enhance jwt signing --- conventional.yaml | 29 +++++++++++------- default.yaml | 28 ++++++++++------- irc/channel.go | 9 ++---- irc/config.go | 55 +++++++++++++++++++++++---------- irc/handlers.go | 48 ++++++++++++++--------------- irc/jwt/extjwt.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 176 insertions(+), 70 deletions(-) create mode 100644 irc/jwt/extjwt.go diff --git a/conventional.yaml b/conventional.yaml index d27ac698..0757f124 100644 --- a/conventional.yaml +++ b/conventional.yaml @@ -161,17 +161,6 @@ server: # - "192.168.1.1" # - "192.168.10.1/24" - # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) - # sometimes referred to with 'EXTJWT' - jwt-services: - # # service name - # call-host: - # # custom expiry length, default is 30s - # expiry-in-seconds: 45 - - # # secret string to verify the generated tokens - # secret: call-hosting-secret-token - # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks allow-plaintext-resume: false @@ -790,6 +779,24 @@ roleplay: # add the real nickname, in parentheses, to the end of every roleplay message? add-suffix: true +# external services can integrate with the ircd using JSON Web Tokens (https://jwt.io). +# in effect, the server can sign a token attesting that the client is present on +# the server, is a member of a particular channel, etc. +extjwt: + # default service config (for `EXTJWT #channel`). + # expiration time for the token: + # expiration: 45s + # you can configure tokens to be signed either with HMAC and a symmetric secret: + # secret: "65PHvk0K1_sM-raTsCEhatVkER_QD8a0zVV8gG2EWcI" + # or with an RSA private key: + # #rsa-private-key-file: "extjwt.pem" + + # named services: + # services: + # "jitsi": + # expiration: 30s + # secret: "qmamLKDuOzIzlO8XqsGGewei_At11lewh6jtKfSTbkg" + # history message storage: this is used by CHATHISTORY, HISTORY, znc.in/playback, # various autoreplay features, and the resume extension history: diff --git a/default.yaml b/default.yaml index 611be84b..9eead870 100644 --- a/default.yaml +++ b/default.yaml @@ -187,17 +187,6 @@ server: # - "192.168.1.1" # - "192.168.10.1/24" - # these services can integrate with the ircd using JSON Web Tokens (https://jwt.io) - # sometimes referred to with 'EXTJWT' - jwt-services: - # # service name - # call-host: - # # custom expiry length, default is 30s - # expiry-in-seconds: 45 - - # # secret string to verify the generated tokens - # secret: call-hosting-secret-token - # allow use of the RESUME extension over plaintext connections: # do not enable this unless the ircd is only accessible over internal networks allow-plaintext-resume: false @@ -816,6 +805,23 @@ roleplay: # add the real nickname, in parentheses, to the end of every roleplay message? add-suffix: true +# external services can integrate with the ircd using JSON Web Tokens (https://jwt.io). +# in effect, the server can sign a token attesting that the client is present on +# the server, is a member of a particular channel, etc. +extjwt: + # default service: + # expiration: 45s + # symmetric secret for HMAC signing: + # secret: "65PHvk0K1_sM-raTsCEhatVkER_QD8a0zVV8gG2EWcI" + # private key for RSA signing: + # rsa-private-key-file: "extjwt.pem" + + # named services: + # services: + # "jitsi": + # expiration: 30s + # secret: "qmamLKDuOzIzlO8XqsGGewei_At11lewh6jtKfSTbkg" + # history message storage: this is used by CHATHISTORY, HISTORY, znc.in/playback, # various autoreplay features, and the resume extension history: diff --git a/irc/channel.go b/irc/channel.go index 842ddc39..99e1960c 100644 --- a/irc/channel.go +++ b/irc/channel.go @@ -539,16 +539,11 @@ func (channel *Channel) ClientPrefixes(client *Client, isMultiPrefix bool) strin } } -func (channel *Channel) ClientModeStrings(client *Client) (result []string) { +func (channel *Channel) ClientStatus(client *Client) (present bool, cModes modes.Modes) { channel.stateMutex.RLock() defer channel.stateMutex.RUnlock() modes, present := channel.members[client] - if present { - for _, mode := range modes.AllModes() { - result = append(result, mode.String()) - } - } - return + return present, modes.AllModes() } func (channel *Channel) ClientHasPrivsOver(client *Client, target *Client) bool { diff --git a/irc/config.go b/irc/config.go index cc81792f..fe5c643f 100644 --- a/irc/config.go +++ b/irc/config.go @@ -27,6 +27,7 @@ import ( "github.com/oragono/oragono/irc/custime" "github.com/oragono/oragono/irc/email" "github.com/oragono/oragono/irc/isupport" + "github.com/oragono/oragono/irc/jwt" "github.com/oragono/oragono/irc/languages" "github.com/oragono/oragono/irc/ldap" "github.com/oragono/oragono/irc/logger" @@ -471,11 +472,6 @@ type TorListenersConfig struct { MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"` } -type JwtServiceConfig struct { - ExpiryInSeconds int64 `yaml:"expiry-in-seconds"` - Secret string -} - // Config defines the overall configuration. type Config struct { Network struct { @@ -507,9 +503,8 @@ type Config struct { MOTDFormatting bool `yaml:"motd-formatting"` ProxyAllowedFrom []string `yaml:"proxy-allowed-from"` proxyAllowedFromNets []net.IPNet - WebIRC []webircConfig `yaml:"webirc"` - JwtServices map[string]JwtServiceConfig `yaml:"jwt-services"` - MaxSendQString string `yaml:"max-sendq"` + WebIRC []webircConfig `yaml:"webirc"` + MaxSendQString string `yaml:"max-sendq"` MaxSendQBytes int AllowPlaintextResume bool `yaml:"allow-plaintext-resume"` Compatibility struct { @@ -537,6 +532,11 @@ type Config struct { addSuffix bool } + Extjwt struct { + Default jwt.JwtServiceConfig `yaml:",inline"` + Services map[string]jwt.JwtServiceConfig `yaml:"services"` + } + Languages struct { Enabled bool Path string @@ -811,6 +811,29 @@ func (conf *Config) prepareListeners() (err error) { return nil } +func (config *Config) processExtjwt() (err error) { + // first process the default service, which may be disabled + err = config.Extjwt.Default.Postprocess() + if err != nil { + return + } + // now process the named services. it is an error if any is disabled + // also, normalize the service names to lowercase + services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services)) + for service, sConf := range config.Extjwt.Services { + err := sConf.Postprocess() + if err != nil { + return err + } + if !sConf.Enabled() { + return fmt.Errorf("no keys enabled for extjwt service %s", service) + } + services[strings.ToLower(service)] = sConf + } + config.Extjwt.Services = services + return nil +} + // LoadRawConfig loads the config without doing any consistency checks or postprocessing func LoadRawConfig(filename string) (config *Config, err error) { data, err := ioutil.ReadFile(filename) @@ -927,13 +950,6 @@ func LoadConfig(filename string) (config *Config, err error) { config.Server.capValues[caps.Multiline] = multilineCapValue } - // confirm jwt config - for name, info := range config.Server.JwtServices { - if info.Secret == "" { - return nil, fmt.Errorf("Could not parse jwt-services config, %s service has no secret set", name) - } - } - // handle legacy name 'bouncer' for 'multiclient' section: if config.Accounts.Bouncer != nil { config.Accounts.Multiclient = *config.Accounts.Bouncer @@ -1153,6 +1169,11 @@ func LoadConfig(filename string) (config *Config, err error) { } } + err = config.processExtjwt() + if err != nil { + return nil, err + } + // now that all postprocessing is complete, regenerate ISUPPORT: err = config.generateISupport() if err != nil { @@ -1190,7 +1211,9 @@ func (config *Config) generateISupport() (err error) { isupport.Add("CHANTYPES", chanTypes) isupport.Add("ELIST", "U") isupport.Add("EXCEPTS", "") - isupport.Add("EXTJWT", "1") + if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 { + isupport.Add("EXTJWT", "1") + } isupport.Add("INVEX", "") isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen)) isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes))) diff --git a/irc/handlers.go b/irc/handlers.go index c0decf2d..3d558cfa 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -20,12 +20,12 @@ import ( "strings" "time" - "github.com/dgrijalva/jwt-go" "github.com/goshuirc/irc-go/ircfmt" "github.com/goshuirc/irc-go/ircmsg" "github.com/oragono/oragono/irc/caps" "github.com/oragono/oragono/irc/custime" "github.com/oragono/oragono/irc/history" + "github.com/oragono/oragono/irc/jwt" "github.com/oragono/oragono/irc/modes" "github.com/oragono/oragono/irc/sno" "github.com/oragono/oragono/irc/utils" @@ -914,8 +914,6 @@ func dlineHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Res // EXTJWT [service_name] func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *ResponseBuffer) bool { - expireInSeconds := int64(30) - accountName := client.AccountName() if accountName == "*" { accountName = "" @@ -938,42 +936,42 @@ func extjwtHandler(server *Server, client *Client, msg ircmsg.IrcMessage, rb *Re claims["channel"] = channel.Name() claims["joined"] = 0 claims["cmodes"] = []string{} - if channel.hasClient(client) { + if present, cModes := channel.ClientStatus(client); present { claims["joined"] = 1 - claims["cmodes"] = channel.ClientModeStrings(client) + var modeStrings []string + for _, cMode := range cModes { + modeStrings = append(modeStrings, string(cMode)) + } + claims["cmodes"] = modeStrings } } - // we default to a secret of `*`. if you want a real secret setup a service in the config~ - service := "*" - secret := "*" + config := server.Config() + var serviceName string + var sConfig jwt.JwtServiceConfig if 1 < len(msg.Params) { - service = strings.ToLower(msg.Params[1]) - - c := server.Config() - info, exists := c.Server.JwtServices[service] - if !exists { - rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service")) - return false - } - secret = info.Secret - if info.ExpiryInSeconds != 0 { - expireInSeconds = info.ExpiryInSeconds - } + serviceName = strings.ToLower(msg.Params[1]) + sConfig = config.Extjwt.Services[serviceName] + } else { + serviceName = "*" + sConfig = config.Extjwt.Default } - claims["exp"] = time.Now().Unix() + expireInSeconds - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - tokenString, err := token.SignedString([]byte(secret)) + if !sConfig.Enabled() { + rb.Add(nil, server.name, "FAIL", "EXTJWT", "NO_SUCH_SERVICE", client.t("No such service")) + return false + } + + tokenString, err := sConfig.Sign(claims) if err == nil { maxTokenLength := 400 for maxTokenLength < len(tokenString) { - rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, "*", tokenString[:maxTokenLength]) + rb.Add(nil, server.name, "EXTJWT", msg.Params[0], serviceName, "*", tokenString[:maxTokenLength]) tokenString = tokenString[maxTokenLength:] } - rb.Add(nil, server.name, "EXTJWT", msg.Params[0], service, tokenString) + rb.Add(nil, server.name, "EXTJWT", msg.Params[0], serviceName, tokenString) } else { rb.Add(nil, server.name, "FAIL", "EXTJWT", "UNKNOWN_ERROR", client.t("Could not generate EXTJWT token")) } diff --git a/irc/jwt/extjwt.go b/irc/jwt/extjwt.go new file mode 100644 index 00000000..803f83e5 --- /dev/null +++ b/irc/jwt/extjwt.go @@ -0,0 +1,77 @@ +// Copyright (c) 2020 Daniel Oaks +// Copyright (c) 2020 Shivaram Lingamneni +// released under the MIT license + +package jwt + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "io/ioutil" + "time" + + "github.com/dgrijalva/jwt-go" +) + +var ( + ErrNoKeys = errors.New("No signing keys are enabled") +) + +type MapClaims jwt.MapClaims + +type JwtServiceConfig struct { + Expiration time.Duration + Secret string + secretBytes []byte + RSAPrivateKeyFile string `yaml:"rsa-private-key-file"` + rsaPrivateKey *rsa.PrivateKey +} + +func (t *JwtServiceConfig) Postprocess() (err error) { + t.secretBytes = []byte(t.Secret) + t.Secret = "" + if t.RSAPrivateKeyFile != "" { + keyBytes, err := ioutil.ReadFile(t.RSAPrivateKeyFile) + if err != nil { + return err + } + d, _ := pem.Decode(keyBytes) + if err != nil { + return err + } + t.rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(d.Bytes) + if err != nil { + privateKey, err := x509.ParsePKCS8PrivateKey(d.Bytes) + if err != nil { + return err + } + if rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey); ok { + t.rsaPrivateKey = rsaPrivateKey + } else { + return fmt.Errorf("Non-RSA key type for extjwt: %T", privateKey) + } + } + } + return nil +} + +func (t *JwtServiceConfig) Enabled() bool { + return t.Expiration != 0 && (len(t.secretBytes) != 0 || t.rsaPrivateKey != nil) +} + +func (t *JwtServiceConfig) Sign(claims MapClaims) (result string, err error) { + claims["exp"] = time.Now().Unix() + int64(t.Expiration/time.Second) + + if t.rsaPrivateKey != nil { + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims)) + return token.SignedString(t.rsaPrivateKey) + } else if len(t.secretBytes) != 0 { + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(claims)) + return token.SignedString(t.secretBytes) + } else { + return "", ErrNoKeys + } +} From a3d288d167db456786dc67837bcf9e13abe84b87 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Tue, 16 Jun 2020 08:51:46 +1000 Subject: [PATCH 017/329] New translations irc.lang.json (Romanian) --- languages/ro-RO-irc.lang.json | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/languages/ro-RO-irc.lang.json b/languages/ro-RO-irc.lang.json index 8bcef135..7eb3d5a0 100644 --- a/languages/ro-RO-irc.lang.json +++ b/languages/ro-RO-irc.lang.json @@ -17,9 +17,9 @@ "%s joined the channel": "%s a intrat pe canal", "*** $bChanServ LIST$b ***": "*** $bLIST pentru ChanServ$b ***", "*** $bEnd of %s HELP$b ***": "*** $bSfârșit ajutor %s$b ***", - "*** $bEnd of ChanServ LIST$b ***": "", - "*** $bEnd of NickServ LIST$b ***": "", - "*** $bNickServ LIST$b ***": "", + "*** $bEnd of ChanServ LIST$b ***": "*** $bSfârșit LIST ChanServ$b ***", + "*** $bEnd of NickServ LIST$b ***": "*** $bSfârșit LIST NickServ$b ***", + "*** $bNickServ LIST$b ***": "*** $bLIST pentru NickServ$b ***", "*** Could not find your username": "*** Nu ți-am găsit numele de utilizator", "*** Found your username": "*** Ți-am găsit numele de utilizator", "*** Got a malformed username, ignoring": "*** Am primit un nume de utilizator deformat, se ignoră", @@ -62,7 +62,7 @@ "Cannot resume connection, connection registration has already been completed": "Nu s-a putut relua conexiunea, înregistrarea conexiunii a fost deja finalizată", "Cannot resume connection, old and new clients must have TLS": "Nu pot relua conexiunea, ambii clienți, vechi și nou, trebuie să aibă TLS", "Cannot resume connection, token is not valid": "Nu se poate relua conexiunea, jetonul este invalid", - "Cannot send a blank line with the multiline concat tag": "", + "Cannot send a blank line with the multiline concat tag": "Nu se poate trimite o linie goală cu marcajul concatenare multi-linie", "Cannot send to channel": "Nu poți trimite pe canal", "Cannot send to channel (+%s)": "Nu poți trimite pe canal (+%s)", "Certfp: %s": "Certfp: %s", @@ -82,7 +82,7 @@ "Channel doesn't have roleplaying mode available": "Nu este disponibil fanionul roleplay pe canal", "Channel is not registered": "Canalul nu este înregistrat", "Channel list is full": "Lista canalelor este plină", - "Channel registration is restricted to server operators": "", + "Channel registration is restricted to server operators": "Procesul de înregistrare a canalelor este disponibil doar pentru operatorii rețelei", "Channel renamed": "Canalul a fost redenumit", "Channel renamed: %s": "Canal redenumit: %s", "Channels with persistent history cannot be renamed": "Canalele cu istoric persistent nu pot fi redenumite", @@ -95,11 +95,11 @@ "Could not accept ownership of channel %s": "Nu s-a putut accepta rolul de fondator al canalului %s", "Could not delete message": "Mesajul nu a putut fi șters", "Could not find given client": "Nu găsesc clientul menționat", - "Could not look up account name, proceeding anyway": "", + "Could not look up account name, proceeding anyway": "Nu am putut găsi numele de cont, continuăm oricum", "Could not parse IP address or CIDR network": "Nu s-a putut analiza adresa IP sau rețeaua CIDR", "Could not register": "Eroare la înregistrare", "Could not remove ban [%s]": "Nu pot înlătura ban [%s]", - "Could not retrieve history": "", + "Could not retrieve history": "Nu se poate obține istoricul", "Could not set or change nickname: %s": "Nu pot seta sau schimba pseudonim: %s", "Could not successfully save new D-LINE: %s": "N-am putut salva noul D-LINE: %s", "Could not successfully save new K-LINE: %s": "N-am putut salva noul K-LINE: %s", @@ -117,13 +117,13 @@ "End of NAMES list": "Sfârșit listă NAMES", "End of WHO list": "Sfârșit listă WHO", "End of WHOWAS": "Sfârșit WHOWAS", - "End of history playback": "", + "End of history playback": "Sfârșitul redării istoricului", "End of list": "Sfârșit listă", "Enqueued account %s for message deletion": "", "Erroneous nickname": "Pseudonim eronat", "Error deleting message: %v": "Eroare la ștergerea mesajului: %v", "Error loading account data": "A apărut o eroare la încărcarea datelor contului", - "Error opening export file: %v": "", + "Error opening export file: %v": "A apărut o eroare la deschiderea fișierului de export: %v", "Error reserving nickname": "Eroare la rezervarea pseudonimului", "Error while unregistering account": "Eroare la ștergerea contului", "Fake source must be a valid nickname": "Sursa falsă trebuie să fie un pseudonim valabil", @@ -163,7 +163,7 @@ "Invalid parameters": "Parametri invalizi", "Invalid parameters. For usage, do /msg %[1]s HELP %[2]s": "Parametri invalizi. Pentru utilizare, încearcă /msg %[1]s HELP %[2]s", "Invalid params": "Parametri invalizi", - "Invalid regex": "", + "Invalid regex": "Expresie regulară invalidă", "Invalid vhost": "Gazdă virtuală invalidă", "It was rejected for reason: %s": "Motivul respingerii a fost următorul: %s", "JOIN 0 is not allowed": "JOIN 0 nu este permis", @@ -273,7 +273,7 @@ "This command has been disabled by the server administrators": "Această comandă a fost dezactivată de echipa administrativă", "This feature has been disabled by the server administrators": "Acest atribut a fost dezactivat de administratorii serverului", "This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect.": "Acest server funcționează în modul de depanare și jurnalizare ale tuturor I/O ale utilizatorilor. Dacă nu dorești ca fiecare mesaj trimis să fie citit de către proprietarul serverului, te rugăm să te deconectezi.", - "This server requires that you wait %v after connecting before you can use /LIST. You have %v left.": "", + "This server requires that you wait %v after connecting before you can use /LIST. You have %v left.": "Serverul este configurat astfel încât trebuie să treacă %v după conectare, până să poți utiliza comanda /LIST. Au mai rămas %v.", "This server was created %s": "Acest server a fost creat la data de %s", "This vhost is currently disabled, but can be enabled with /HS ON": "Gazda dumneavoastră virtuală este dezactivată, dar poate fi activată cu comanda /HS ON", "Timestamp is not in 2006-01-02T15:04:05.999Z format, ignoring it": "Marcajul de timp nu este în formatul 2006-01-02T15:04:05.999Z, se ignoră", From 57586a9548301a1c69ddf15ce7742869a0c54836 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Tue, 16 Jun 2020 08:51:47 +1000 Subject: [PATCH 018/329] New translations help.lang.json (Romanian) --- languages/ro-RO-help.lang.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/languages/ro-RO-help.lang.json b/languages/ro-RO-help.lang.json index 6f6a1938..614293ab 100644 --- a/languages/ro-RO-help.lang.json +++ b/languages/ro-RO-help.lang.json @@ -1,7 +1,7 @@ { "= Help Topics =\n\nCommands:\n%[1]s\n\nRPL_ISUPPORT Tokens:\n%[2]s\n\nInformation:\n%[3]s": "= Tematică de ajutor=\n\nComenzi:\n%[1]s\n\nJetoane RPL_ISUPPORT:\n%[2]s\n\nInformație:\n%[3]s", - "== Channel Modes ==\n\nOragono supports the following channel modes:\n\n +b | Client masks that are banned from the channel (e.g. *!*@127.0.0.1)\n +e | Client masks that are exempted from bans.\n +I | Client masks that are exempted from the invite-only flag.\n +i | Invite-only mode, only invited clients can join the channel.\n +k | Key required when joining the channel.\n +l | Client join limit for the channel.\n +m | Moderated mode, only privileged clients can talk on the channel.\n +n | No-outside-messages mode, only users that are on the channel can send\n | messages to it.\n +R | Only registered users can join the channel.\n +s | Secret mode, channel won't show up in /LIST or whois replies.\n +t | Only channel opers can modify the topic.\n\n= Prefixes =\n\n +q (~) | Founder channel mode.\n +a (&) | Admin channel mode.\n +o (@) | Operator channel mode.\n +h (%) | Halfop channel mode.\n +v (+) | Voice channel mode.": "", - "== Server Notice Masks ==\n\nOragono supports the following server notice masks for operators:\n\n a | Local announcements.\n c | Local client connections.\n j | Local channel actions.\n k | Local kills.\n n | Local nick changes.\n o | Local oper actions.\n q | Local quits.\n t | Local /STATS usage.\n u | Local client account actions.\n x | Local X-lines (DLINE/KLINE/etc).\n v | Local vhost changes.\n\nTo set a snomask, do this with your nickname:\n\n /MODE +s \n\nFor instance, this would set the kill, oper, account and xline snomasks on dan:\n\n /MODE dan +s koux": "", + "== Channel Modes ==\n\nOragono supports the following channel modes:\n\n +b | Client masks that are banned from the channel (e.g. *!*@127.0.0.1)\n +e | Client masks that are exempted from bans.\n +I | Client masks that are exempted from the invite-only flag.\n +i | Invite-only mode, only invited clients can join the channel.\n +k | Key required when joining the channel.\n +l | Client join limit for the channel.\n +m | Moderated mode, only privileged clients can talk on the channel.\n +n | No-outside-messages mode, only users that are on the channel can send\n | messages to it.\n +R | Only registered users can join the channel.\n +s | Secret mode, channel won't show up in /LIST or whois replies.\n +t | Only channel opers can modify the topic.\n\n= Prefixes =\n\n +q (~) | Founder channel mode.\n +a (&) | Admin channel mode.\n +o (@) | Operator channel mode.\n +h (%) | Halfop channel mode.\n +v (+) | Voice channel mode.": "== Moduri de canal ==\n\nOragono suportă următoarele moduri de canal:\n\n +b | Măștile unui client, interzise pe canal (ex. *!*@127.0.0.1)\n +e | Măștile unui client, ce fac excepție de la ban.\n +I | Măștile unui client, ce fac excepție de la fanionul numai-invitație.\n +i | Fanion doar-invitație, doar clienții invitați pot intra pe canal.\n +k | Este necesară o cheie, pentru a putea intra pe canal.\n +l | Limită de clienți ce se pot alătura canalului.\n +m | Modul moderat, doar clienții privilegiați pot discuta pe canal.\n +n | Modul fără-mesaje-din-afară, doar utilizatorii care se află pe canal\n | pot trimite mesaje.\n +R | Doar utilizatorii înregistrați la servicii pot intra pe canal.\n +s | Mod secret, canalul nu va fi afișat în /LIST sau mesaje whois.\n +t | Doar operatorii canalului pot modifica topicul.\n\n= Prefixe =\n\n +q (~) | Mod fondator de canal.\n +a (&) | Mod administrator de canal.\n +o (@) | Mod operator de canal.\n +h (%) | Mod semi-op pe canal.\n +v (+) | Mod voce pe canal.", + "== Server Notice Masks ==\n\nOragono supports the following server notice masks for operators:\n\n a | Local announcements.\n c | Local client connections.\n j | Local channel actions.\n k | Local kills.\n n | Local nick changes.\n o | Local oper actions.\n q | Local quits.\n t | Local /STATS usage.\n u | Local client account actions.\n x | Local X-lines (DLINE/KLINE/etc).\n v | Local vhost changes.\n\nTo set a snomask, do this with your nickname:\n\n /MODE +s \n\nFor instance, this would set the kill, oper, account and xline snomasks on dan:\n\n /MODE dan +s koux": "== Măști de atenționare de server ==\n\nOragono suportă următoarele măști de atenționare valabile pentru operatori:\n\n a | Anunțuri locale.\n c | Conexiuni clienți locali.\n j | Acțiuni canale locale.\n k | Kill locale.\n n | Schimbări locale de pseudonime.\n o | Acțiuni operatori locali.\n q | Renunțări locale.\n t | Utilizare /STATS local.\n u | Local client account actions.\n x | X-lines (DLINE/KLINE/etc) locale.\n v | Modificări locale ale gazdei virtuale.\n\nPentru a seta o mască de atenționare, setează-ți pe pseudonim:\n\n /MODE +s \n\nSpre exemplu, următoarea comandă va seta modurile kill, oper, cont și xline pentru utilizatorul dan:\n\n /MODE dan +s koux", "== User Modes ==\n\nOragono supports the following user modes:\n\n +a | User is marked as being away. This mode is set with the /AWAY command.\n +i | User is marked as invisible (their channels are hidden from whois replies).\n +o | User is an IRC operator.\n +R | User only accepts messages from other registered users. \n +s | Server Notice Masks (see help with /HELPOP snomasks).\n +Z | User is connected via TLS.": "== Moduri utilizator ==\n\nOragono suportă următoarele moduri(fanioane) de utilizator:\n\n +a | Utilizatorul a fost marcat ca fiind fără activitate. Acest fanion poate fi setat cu comanda /AWAY.\n +i | Utilizatorul a fost marcat ca invizibil (canalele pe care se află vor fi ascunse în conținutul /whois).\n +o | Utilizatorul este un Operator IRC.\n +R | Utilizatorul acceptă mesaje doar de la alți utilizatori înregistrați. \n +s | Măști de Anunț de Server (vezi informații de ajutor cu comanda /HELPOP snomasks).\n +Z | Utilizatorul se conectează via TLS.", "@+client-only-tags TAGMSG {,}\n\nSends the given client-only tags to the given targets as a TAGMSG. See the IRCv3\nspecs for more info: http://ircv3.net/specs/core/message-tags-3.3.html": "@+client-only-tags TAGMSG <țintă>{,<țintă>}\n\nExpediază marcajele client-doar către țintele precizate ca și TAGMSG.\nVezi specificațiile IRCv3, iar pentru mai multe informații, accesează acest link:\nhttp://ircv3.net/specs/core/message-tags-3.3.html", "ACC LS\nACC REGISTER [callback_namespace:] [cred_type] :\nACC VERIFY \n\nUsed in account registration. See the relevant specs for more info:\nhttps://oragono.io/specs.html": "ACC LS\nACC REGISTER [callback_namespace:] [tip credențiale] :\nACC VERIFY \n\nSe utilizează la înregistrarea de conturi. Vezi specificațiile relevante\npentru mai multe informații: https://oragono.io/specs.html", From 68faf7926e9a08e0f8827d3f73ddc113cb87450f Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Mon, 15 Jun 2020 22:32:06 -0400 Subject: [PATCH 019/329] review fix --- conventional.yaml | 10 +++++----- default.yaml | 11 ++++++----- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/conventional.yaml b/conventional.yaml index 0757f124..2ce840a7 100644 --- a/conventional.yaml +++ b/conventional.yaml @@ -783,15 +783,15 @@ roleplay: # in effect, the server can sign a token attesting that the client is present on # the server, is a member of a particular channel, etc. extjwt: - # default service config (for `EXTJWT #channel`). - # expiration time for the token: + # # default service config (for `EXTJWT #channel`). + # # expiration time for the token: # expiration: 45s - # you can configure tokens to be signed either with HMAC and a symmetric secret: + # # you can configure tokens to be signed either with HMAC and a symmetric secret: # secret: "65PHvk0K1_sM-raTsCEhatVkER_QD8a0zVV8gG2EWcI" - # or with an RSA private key: + # # or with an RSA private key: # #rsa-private-key-file: "extjwt.pem" - # named services: + # # named services (for `EXTJWT #channel service_name`): # services: # "jitsi": # expiration: 30s diff --git a/default.yaml b/default.yaml index 9eead870..fe30f336 100644 --- a/default.yaml +++ b/default.yaml @@ -809,14 +809,15 @@ roleplay: # in effect, the server can sign a token attesting that the client is present on # the server, is a member of a particular channel, etc. extjwt: - # default service: + # # default service config (for `EXTJWT #channel`). + # # expiration time for the token: # expiration: 45s - # symmetric secret for HMAC signing: + # # you can configure tokens to be signed either with HMAC and a symmetric secret: # secret: "65PHvk0K1_sM-raTsCEhatVkER_QD8a0zVV8gG2EWcI" - # private key for RSA signing: - # rsa-private-key-file: "extjwt.pem" + # # or with an RSA private key: + # #rsa-private-key-file: "extjwt.pem" - # named services: + # # named services (for `EXTJWT #channel service_name`): # services: # "jitsi": # expiration: 30s From 90e697f454ad1fd35bad2f76885daf0cbaa11b6a Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 16 Jun 2020 04:57:49 -0400 Subject: [PATCH 020/329] read device ID from SASL as well --- irc/handlers.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/irc/handlers.go b/irc/handlers.go index 3d558cfa..2804aeb8 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -241,6 +241,9 @@ func authPlainHandler(server *Server, client *Client, mechanism string, value [] // distinguish user/ident from account name if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 { authcid = authcid[:strudelIndex] + if !client.registered { + rb.session.deviceID = authcid[strudelIndex+1:] + } } password := string(splitValue[2]) err := server.accounts.AuthenticateByPassphrase(client, authcid, password) @@ -294,6 +297,9 @@ func authExternalHandler(server *Server, client *Client, mechanism string, value // distinguish user/ident from account name if strudelIndex := strings.IndexByte(authzid, '@'); strudelIndex != -1 { authzid = authzid[:strudelIndex] + if !client.registered { + rb.session.deviceID = authzid[strudelIndex+1:] + } } err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid) } From 784078d6938ee4b8e3ece8c46cf1084f10104873 Mon Sep 17 00:00:00 2001 From: Shivaram Lingamneni Date: Tue, 16 Jun 2020 05:10:09 -0400 Subject: [PATCH 021/329] fix bug introduced in #1138 --- irc/handlers.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/irc/handlers.go b/irc/handlers.go index 2804aeb8..c4f9d515 100644 --- a/irc/handlers.go +++ b/irc/handlers.go @@ -240,9 +240,10 @@ func authPlainHandler(server *Server, client *Client, mechanism string, value [] // see #843: strip the device ID for the benefit of clients that don't // distinguish user/ident from account name if strudelIndex := strings.IndexByte(authcid, '@'); strudelIndex != -1 { - authcid = authcid[:strudelIndex] + var deviceID string + authcid, deviceID = authcid[:strudelIndex], authcid[strudelIndex+1:] if !client.registered { - rb.session.deviceID = authcid[strudelIndex+1:] + rb.session.deviceID = deviceID } } password := string(splitValue[2]) @@ -296,9 +297,10 @@ func authExternalHandler(server *Server, client *Client, mechanism string, value // see #843: strip the device ID for the benefit of clients that don't // distinguish user/ident from account name if strudelIndex := strings.IndexByte(authzid, '@'); strudelIndex != -1 { - authzid = authzid[:strudelIndex] + var deviceID string + authzid, deviceID = authzid[:strudelIndex], authzid[strudelIndex+1:] if !client.registered { - rb.session.deviceID = authzid[strudelIndex+1:] + rb.session.deviceID = deviceID } } err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, authzid) From fb55cc3390ebae3f1c0f00c9349c25ef89cbdd86 Mon Sep 17 00:00:00 2001 From: Daniel Oaks Date: Tue, 16 Jun 2020 20:33:10 +1000 Subject: [PATCH 022/329] Ignore some dodgy TL strings, fix another dodgy string --- irc/chanserv.go | 2 +- languages/example/help.lang.json | 3 +++ languages/example/irc.lang.json | 9 ++++++- languages/example/nickserv.lang.json | 5 ++-- updatetranslations.py | 39 ++++++++++++++++++++++++++++ 5 files changed, 53 insertions(+), 5 deletions(-) diff --git a/irc/chanserv.go b/irc/chanserv.go index d5622828..e21a44dc 100644 --- a/irc/chanserv.go +++ b/irc/chanserv.go @@ -249,7 +249,7 @@ func csAmodeHandler(server *Server, client *Client, command string, params []str } case modes.Add, modes.Remove: if len(affectedModes) > 0 { - csNotice(rb, fmt.Sprintf(client.t("Successfully set persistent mode %s%s on %s"), string(change.Op), string(change.Mode), change.Arg)) + csNotice(rb, fmt.Sprintf(client.t("Successfully set persistent mode %[1]s on %[2]s"), strings.Join([]string{string(change.Op), string(change.Mode)}, ""), change.Arg)) // #729: apply change to current membership for _, member := range channel.Members() { if member.Account() == change.Arg { diff --git a/languages/example/help.lang.json b/languages/example/help.lang.json index 1cf60574..36228789 100644 --- a/languages/example/help.lang.json +++ b/languages/example/help.lang.json @@ -15,6 +15,7 @@ "DEBUG