Files
mattermost/utils/license.go

229 lines
6.2 KiB
Go
Raw Normal View History

// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
2016-01-04 12:44:22 -05:00
// See License.txt for license information.
package utils
import (
"crypto"
"crypto/md5"
2016-01-04 12:44:22 -05:00
"crypto/rsa"
2016-01-14 08:23:48 -05:00
"crypto/sha512"
2016-01-04 12:44:22 -05:00
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
2016-01-04 12:44:22 -05:00
"strconv"
"strings"
2016-01-14 09:54:15 -05:00
l4g "github.com/alecthomas/log4go"
2016-01-04 12:44:22 -05:00
"github.com/mattermost/platform/model"
)
var IsLicensed bool = false
PLT-2057 User as a first class object (#2648) * Adding TeamMember to system * Fixing all unit tests on the backend * Fixing merge conflicts * Fixing merge conflict * Adding javascript unit tests * Adding TeamMember to system * Fixing all unit tests on the backend * Fixing merge conflicts * Fixing merge conflict * Adding javascript unit tests * Adding client side unit test * Cleaning up the clint side tests * Fixing msg * Adding more client side unit tests * Adding more using tests * Adding last bit of client side unit tests and adding make cmd * Fixing bad merge * Fixing libraries * Updating to new client side API * Fixing borken unit test * Fixing unit tests * ugg...trying to beat gofmt * ugg...trying to beat gofmt * Cleaning up remainder of the server side routes * Adding inital load api * Increased coverage of webhook unit tests (#2660) * Adding loading ... to root html * Fixing bad merge * Removing explicit content type so superagent will guess corectly (#2685) * Fixing merge and unit tests * Adding create team UI * Fixing signup flows * Adding LDAP unit tests and enterprise unit test helper (#2702) * Add the ability to reset MFA from the commandline (#2706) * Fixing compliance unit tests * Fixing client side tests * Adding open server to system console * Moving websocket connection * Fixing unit test * Fixing unit tests * Fixing unit tests * Adding nickname and more LDAP unit tests (#2717) * Adding join open teams * Cleaning up all TODOs in the code * Fixing web sockets * Removing unused webockets file * PLT-2533 Add the ability to reset a user's MFA from the system console (#2715) * Add the ability to reset a user's MFA from the system console * Add client side unit test for adminResetMfa * Reorganizing authentication to fix LDAP error message (#2723) * Fixing failing unit test * Initial upgrade db code * Adding upgrade script * Fixing upgrade script after running on core * Update OAuth and Claim routes to work with user model changes (#2739) * Fixing perminant deletion. Adding ability to delete all user and the entire database (#2740) * Fixing team invite ldap login call (#2741) * Fixing bluebar and some img stuff * Fix all the different file upload web utils (#2743) * Fixing invalid session redirect (#2744) * Redirect on bad channel name (#2746) * Fixing a bunch of issue and removing dead code * Patch to fix error message on leave channel (#2747) * Setting EnableOpenServer to false by default * Fixing config * Fixing upgrade * Fixing reported bugs * Bug fixes for PLT-2057 * PLT-2563 Redo password recovery to use a database table (#2745) * Redo password recovery to use a database table * Update reset password audits * Split out admin and user reset password APIs to be separate * Delete password recovery when user is permanently deleted * Consolidate password resetting into a single function * Removed private channels as an option for outgoing webhooks (#2752) * PLT-2577/PLT-2552 Fixes for backstage (#2753) * Added URL to incoming webhook list * Fixed client functions for adding/removing integrations * Disallowed slash commands without trigger words * Fixed clientside handling of errors on AddCommand page * Minor auth cleanup (#2758) * Changed EditPostModal to just close if you save without making any changes (#2759) * Renamed client -> Client in async_client.jsx and fixed eslint warnings (#2756) * Fixed url in channel info modal (#2755) * Fixing reported issues * Moving to version 3 of the apis * Fixing command unit tests (#2760) * Adding team admins * Fixing DM issue * Fixing eslint error * Properly set EditPostModal's originalText state in all cases (#2762) * Update client config check to assume features is defined if server is licensed (#2772) * Fixing url link * Fixing issue with websocket crashing when sending messages to different teams
2016-04-21 22:37:01 -07:00
var License *model.License = &model.License{
Features: new(model.Features),
}
2016-02-08 07:26:10 -05:00
var ClientLicense map[string]string = map[string]string{"IsLicensed": "false"}
2016-01-04 12:44:22 -05:00
var publicKey []byte = []byte(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyZmShlU8Z8HdG0IWSZ8r
tSyzyxrXkJjsFUf0Ke7bm/TLtIggRdqOcUF3XEWqQk5RGD5vuq7Rlg1zZqMEBk8N
EZeRhkxyaZW8pLjxwuBUOnXfJew31+gsTNdKZzRjrvPumKr3EtkleuoxNdoatu4E
HrKmR/4Yi71EqAvkhk7ZjQFuF0osSWJMEEGGCSUYQnTEqUzcZSh1BhVpkIkeu8Kk
1wCtptODixvEujgqVe+SrE3UlZjBmPjC/CL+3cYmufpSNgcEJm2mwsdaXp2OPpfn
a0v85XL6i9ote2P+fLZ3wX9EoioHzgdgB7arOxY50QRJO7OyCqpKFKv6lRWTXuSt
hwIDAQAB
2016-01-04 12:44:22 -05:00
-----END PUBLIC KEY-----`)
2016-02-04 13:00:03 -05:00
func LoadLicense(licenseBytes []byte) {
if success, licenseStr := ValidateLicense(licenseBytes); success {
2016-01-04 12:44:22 -05:00
license := model.LicenseFromJson(strings.NewReader(licenseStr))
2016-01-14 08:23:48 -05:00
SetLicense(license)
return
2016-01-04 12:44:22 -05:00
}
l4g.Warn(T("utils.license.load_license.invalid.warn"))
2016-01-04 12:44:22 -05:00
}
func SetLicense(license *model.License) bool {
2016-01-14 08:23:48 -05:00
license.Features.SetDefaults()
if !license.IsExpired() {
2016-01-04 12:44:22 -05:00
License = license
IsLicensed = true
ClientLicense = getClientLicense(license)
ClientCfg = getClientConfig(Cfg)
2016-01-04 12:44:22 -05:00
return true
}
return false
}
2016-02-04 13:00:03 -05:00
func RemoveLicense() {
2016-01-04 12:44:22 -05:00
License = &model.License{}
IsLicensed = false
ClientLicense = getClientLicense(License)
ClientCfg = getClientConfig(Cfg)
2016-01-04 12:44:22 -05:00
}
func ValidateLicense(signed []byte) (bool, string) {
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(signed)))
_, err := base64.StdEncoding.Decode(decoded, signed)
if err != nil {
l4g.Error(T("utils.license.validate_license.decode.error"), err.Error())
2016-01-04 12:44:22 -05:00
return false, ""
}
if len(decoded) <= 256 {
l4g.Error(T("utils.license.validate_license.not_long.error"))
2016-01-04 12:44:22 -05:00
return false, ""
}
// remove null terminator
for decoded[len(decoded)-1] == byte(0) {
2016-01-04 12:44:22 -05:00
decoded = decoded[:len(decoded)-1]
}
plaintext := decoded[:len(decoded)-256]
signature := decoded[len(decoded)-256:]
block, _ := pem.Decode(publicKey)
public, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
l4g.Error(T("utils.license.validate_license.signing.error"), err.Error())
2016-01-04 12:44:22 -05:00
return false, ""
}
rsaPublic := public.(*rsa.PublicKey)
2016-01-14 08:23:48 -05:00
h := sha512.New()
2016-01-04 12:44:22 -05:00
h.Write(plaintext)
d := h.Sum(nil)
2016-01-14 08:23:48 -05:00
err = rsa.VerifyPKCS1v15(rsaPublic, crypto.SHA512, d, signature)
2016-01-04 12:44:22 -05:00
if err != nil {
l4g.Error(T("utils.license.validate_license.invalid.error"), err.Error())
2016-01-04 12:44:22 -05:00
return false, ""
}
return true, string(plaintext)
}
func GetAndValidateLicenseFileFromDisk() (*model.License, []byte) {
fileName := GetLicenseFileLocation(*Cfg.ServiceSettings.LicenseFileLocation)
if _, err := os.Stat(fileName); err != nil {
l4g.Debug("We could not find the license key in the database or on disk at %v", fileName)
return nil, nil
}
l4g.Info("License key has not been uploaded. Loading license key from disk at %v", fileName)
licenseBytes := GetLicenseFileFromDisk(fileName)
if success, licenseStr := ValidateLicense(licenseBytes); !success {
l4g.Error("Found license key at %v but it appears to be invalid.", fileName)
return nil, nil
} else {
return model.LicenseFromJson(strings.NewReader(licenseStr)), licenseBytes
}
}
func GetLicenseFileFromDisk(fileName string) []byte {
file, err := os.Open(fileName)
if err != nil {
l4g.Error("Failed to open license key from disk at %v err=%v", fileName, err.Error())
return nil
}
defer file.Close()
licenseBytes, err := ioutil.ReadAll(file)
if err != nil {
l4g.Error("Failed to read license key from disk at %v err=%v", fileName, err.Error())
return nil
}
return licenseBytes
}
func GetLicenseFileLocation(fileLocation string) string {
if fileLocation == "" {
configDir, _ := FindDir("config")
return configDir + "mattermost.mattermost-license"
} else {
return fileLocation
}
}
2016-01-04 12:44:22 -05:00
func getClientLicense(l *model.License) map[string]string {
props := make(map[string]string)
props["IsLicensed"] = strconv.FormatBool(IsLicensed)
if IsLicensed {
props["Id"] = l.Id
2016-01-14 08:23:48 -05:00
props["Users"] = strconv.Itoa(*l.Features.Users)
props["LDAP"] = strconv.FormatBool(*l.Features.LDAP)
2016-03-30 12:49:29 -04:00
props["MFA"] = strconv.FormatBool(*l.Features.MFA)
props["SAML"] = strconv.FormatBool(*l.Features.SAML)
props["Cluster"] = strconv.FormatBool(*l.Features.Cluster)
props["Metrics"] = strconv.FormatBool(*l.Features.Metrics)
props["GoogleOAuth"] = strconv.FormatBool(*l.Features.GoogleOAuth)
props["Office365OAuth"] = strconv.FormatBool(*l.Features.Office365OAuth)
2016-03-14 16:07:58 -07:00
props["Compliance"] = strconv.FormatBool(*l.Features.Compliance)
props["CustomBrand"] = strconv.FormatBool(*l.Features.CustomBrand)
2016-05-03 11:54:49 -04:00
props["MHPNS"] = strconv.FormatBool(*l.Features.MHPNS)
props["PasswordRequirements"] = strconv.FormatBool(*l.Features.PasswordRequirements)
props["Announcement"] = strconv.FormatBool(*l.Features.Announcement)
2016-01-04 12:44:22 -05:00
props["IssuedAt"] = strconv.FormatInt(l.IssuedAt, 10)
props["StartsAt"] = strconv.FormatInt(l.StartsAt, 10)
props["ExpiresAt"] = strconv.FormatInt(l.ExpiresAt, 10)
props["Name"] = l.Customer.Name
props["Email"] = l.Customer.Email
props["Company"] = l.Customer.Company
props["PhoneNumber"] = l.Customer.PhoneNumber
}
return props
}
func GetClientLicenseEtag(useSanitized bool) string {
value := ""
lic := ClientLicense
if useSanitized {
lic = GetSanitizedClientLicense()
}
for k, v := range lic {
value += fmt.Sprintf("%s:%s;", k, v)
}
return model.Etag(fmt.Sprintf("%x", md5.Sum([]byte(value))))
}
func GetSanitizedClientLicense() map[string]string {
sanitizedLicense := make(map[string]string)
for k, v := range ClientLicense {
sanitizedLicense[k] = v
}
if IsLicensed {
delete(sanitizedLicense, "Id")
delete(sanitizedLicense, "Name")
delete(sanitizedLicense, "Email")
delete(sanitizedLicense, "PhoneNumber")
delete(sanitizedLicense, "IssuedAt")
delete(sanitizedLicense, "StartsAt")
delete(sanitizedLicense, "ExpiresAt")
}
return sanitizedLicense
}