This repository has been archived by the owner on Oct 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #84 from dbarth/token
Access Token
- Loading branch information
Showing
19 changed files
with
691 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
/* | ||
* Copyright (C) 2016 Canonical Ltd | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU General Public License version 3 as | ||
* published by the Free Software Foundation. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
* | ||
*/ | ||
|
||
package main | ||
|
||
import ( | ||
"crypto/rand" | ||
"fmt" | ||
"io/ioutil" | ||
"log" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
var logger *log.Logger | ||
|
||
var shorHelp = "Creates an accesss token for using Snapweb on this system" | ||
|
||
var longHelp = ` | ||
The generate-token command creates a new access token, to confirm that you are an authorized administrator of this system. | ||
The access token will be requested the first time you try to access the Snapweb interface. | ||
If the token expired or became invalid, you can use the command again to generate a new one. | ||
` | ||
|
||
func tokenFilename() string { | ||
return filepath.Join(os.Getenv("SNAP_DATA"), "token.txt") | ||
} | ||
|
||
// checkUser verifies that the user running the command is administrator | ||
func checkUser() { | ||
if os.Geteuid() != 0 { | ||
fmt.Println("You need administrator privileges to run this command. Use:\n\nsudo snapweb.generate-token") | ||
os.Exit(1) | ||
} | ||
} | ||
|
||
// writeToken saves the token for later comparison by the snapweb token handler | ||
func writeToken(token string) { | ||
targetFile := tokenFilename() | ||
err := ioutil.WriteFile(targetFile, []byte(token), 0600) | ||
if err != nil { | ||
logger.Fatal(err) | ||
} | ||
} | ||
|
||
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
|
||
func generateToken(n int) string { | ||
// rand.Seed(time.Now().UnixNano()) | ||
|
||
b := make([]byte, n) | ||
_, err := rand.Read(b) | ||
if err != nil { | ||
logger.Fatal(err) | ||
} | ||
for i := range b { | ||
index := int(b[i]) % len(alphabet) | ||
b[i] = alphabet[index] | ||
} | ||
|
||
return string(b) | ||
} | ||
|
||
func saveToken() string { | ||
token := generateToken(64) | ||
writeToken(token) | ||
|
||
return token | ||
} | ||
|
||
func main() { | ||
logger = log.New(os.Stderr, "generate-token: ", log.Ldate|log.Ltime|log.Lshortfile) | ||
|
||
checkUser() | ||
|
||
token := saveToken() | ||
|
||
fmt.Printf("Snapweb Access Token:\n\n%s\n\n", token) | ||
fmt.Printf("Use the above token in the Snapweb interface to be granted access.\n") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/* | ||
* Copyright (C) 2016 Canonical Ltd | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU General Public License version 3 as | ||
* published by the Free Software Foundation. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
* | ||
*/ | ||
|
||
package main | ||
|
||
import ( | ||
"io/ioutil" | ||
"os" | ||
"testing" | ||
|
||
. "gopkg.in/check.v1" | ||
) | ||
|
||
func Test(t *testing.T) { TestingT(t) } | ||
|
||
type GenerateTokenSuite struct { | ||
} | ||
|
||
var _ = Suite(&GenerateTokenSuite{}) | ||
|
||
func (s *GenerateTokenSuite) SetUpTest(c *C) { | ||
os.Setenv("SNAP_DATA", c.MkDir()) | ||
} | ||
|
||
func (s *GenerateTokenSuite) TestCreateDifferentTokens(c *C) { | ||
token1 := generateToken(64) | ||
c.Assert(len(token1), Equals, 64) | ||
for i := 0; i < 100000; i++ { | ||
token2 := generateToken(64) | ||
c.Assert(token1, Not(Equals), token2) | ||
} | ||
} | ||
|
||
func (s *GenerateTokenSuite) TestSaveToken(c *C) { | ||
token := saveToken() | ||
t, err := ioutil.ReadFile(tokenFilename()) | ||
c.Assert(err, IsNil) | ||
c.Assert(string(t), Equals, token) | ||
c.Assert(len(string(t)), Equals, 64) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
/* | ||
* Copyright (C) 2014-2016 Canonical Ltd | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU General Public License version 3 as | ||
* published by the Free Software Foundation. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
* | ||
*/ | ||
|
||
package main | ||
|
||
import ( | ||
"crypto/ecdsa" | ||
"crypto/rand" | ||
"crypto/rsa" | ||
"crypto/x509" | ||
"crypto/x509/pkix" | ||
"encoding/pem" | ||
"log" | ||
"math/big" | ||
"net" | ||
"os" | ||
"time" | ||
) | ||
|
||
func publicKey(priv interface{}) interface{} { | ||
switch k := priv.(type) { | ||
case *rsa.PrivateKey: | ||
return &k.PublicKey | ||
case *ecdsa.PrivateKey: | ||
return &k.PublicKey | ||
default: | ||
return nil | ||
} | ||
} | ||
|
||
func pemBlockForKey(priv interface{}) *pem.Block { | ||
switch k := priv.(type) { | ||
case *rsa.PrivateKey: | ||
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} | ||
case *ecdsa.PrivateKey: | ||
b, err := x509.MarshalECPrivateKey(k) | ||
if err != nil { | ||
log.Fatalf("Unable to marshal ECDSA private key: %v", err) | ||
} | ||
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} | ||
default: | ||
return nil | ||
} | ||
} | ||
|
||
// GenerateCertificate will generate a new self-signed certifiate at startup | ||
func GenerateCertificate() { | ||
/* With help from https://golang.org/src/crypto/tls/generate_cert.go */ | ||
|
||
var priv interface{} | ||
var err error | ||
priv, err = rsa.GenerateKey(rand.Reader, 2048) | ||
if err != nil { | ||
log.Fatalf("failed to generate private key: %s", err) | ||
} | ||
|
||
notBefore := time.Now() | ||
validFor := 365 * 24 * time.Hour | ||
notAfter := notBefore.Add(validFor) | ||
|
||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) | ||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) | ||
if err != nil { | ||
log.Fatalf("failed to generate serial number: %s", err) | ||
} | ||
|
||
template := x509.Certificate{ | ||
SerialNumber: serialNumber, | ||
Subject: pkix.Name{ | ||
Organization: []string{"snapweb"}, | ||
}, | ||
NotBefore: notBefore, | ||
NotAfter: notAfter, | ||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, | ||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, | ||
BasicConstraintsValid: true, | ||
} | ||
|
||
// TODO: add other IP addresses and hostnames (check Avahi) | ||
template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1")) | ||
template.IsCA = false | ||
|
||
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) | ||
if err != nil { | ||
log.Fatalf("Failed to create certificate: %s", err) | ||
} | ||
|
||
certOut, err := os.Create("cert.pem") | ||
if err != nil { | ||
log.Fatalf("failed to open cert.pem for writing: %s", err) | ||
} | ||
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) | ||
certOut.Close() | ||
|
||
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) | ||
if err != nil { | ||
log.Fatal("failed to open key.pem for writing:", err) | ||
} | ||
|
||
pem.Encode(keyOut, pemBlockForKey(priv)) | ||
keyOut.Close() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
/* | ||
* Copyright (C) 2016 Canonical Ltd | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU General Public License version 3 as | ||
* published by the Free Software Foundation. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
* | ||
*/ | ||
|
||
package main | ||
|
||
import ( | ||
"io/ioutil" | ||
"os" | ||
"path/filepath" | ||
|
||
. "gopkg.in/check.v1" | ||
) | ||
|
||
type CertSuite struct{} | ||
|
||
var _ = Suite(&CertSuite{}) | ||
|
||
func (s *CertSuite) TestGenerate(c *C) { | ||
tmp := c.MkDir() | ||
os.Setenv("SNAP_DATA", tmp) | ||
certFile := filepath.Join(os.Getenv("SNAP_DATA"), "cert.pem") | ||
keyFile := filepath.Join(os.Getenv("SNAP_DATA"), "key.pem") | ||
|
||
c.Assert(ioutil.WriteFile(certFile, nil, 0600), IsNil) | ||
c.Assert(ioutil.WriteFile(keyFile, nil, 0600), IsNil) | ||
|
||
GenerateCertificate() | ||
_, err := ioutil.ReadFile(certFile) | ||
c.Assert(err, IsNil) | ||
_, err = ioutil.ReadFile(keyFile) | ||
c.Assert(err, IsNil) | ||
} |
Oops, something went wrong.