Skip to content
This repository has been archived by the owner on Oct 4, 2023. It is now read-only.

Commit

Permalink
Merge pull request #84 from dbarth/token
Browse files Browse the repository at this point in the history
Access Token
  • Loading branch information
mvo5 authored Oct 20, 2016
2 parents 77e8955 + 6202bff commit 3f4cf94
Show file tree
Hide file tree
Showing 19 changed files with 691 additions and 8 deletions.
3 changes: 3 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ gobuild() {
mkdir -p $output_dir
cd $output_dir
GOARCH=$arch GOARM=7 CGO_ENABLED=1 CC=${plat_abi}-gcc go build -ldflags "-extld=${plat_abi}-gcc" github.com/snapcore/snapweb/cmd/snapweb
GOARCH=$arch GOARM=7 CGO_ENABLED=1 CC=${plat_abi}-gcc go build -o generate-token -ldflags "-extld=${plat_abi}-gcc" $srcdir/cmd/generate-token/main.go
cd - > /dev/null
}

Expand All @@ -60,10 +61,12 @@ go get launchpad.net/godeps
godeps -u dependencies.tsv

# build one snap per arch
# for ARCH in amd64 ; do
for ARCH in amd64 arm64 armhf i386; do
builddir="${top_builddir}/${ARCH}"
mkdir -p "$builddir"

srcdir=`pwd`
cp -r pkg/. ${builddir}/
mkdir $builddir/www
cp -r www/public www/templates $builddir/www
Expand Down
96 changes: 96 additions & 0 deletions cmd/generate-token/main.go
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")
}
54 changes: 54 additions & 0 deletions cmd/generate-token/main_test.go
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)
}
116 changes: 116 additions & 0 deletions cmd/snapweb/cert.go
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()
}
46 changes: 46 additions & 0 deletions cmd/snapweb/cert_test.go
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)
}
Loading

0 comments on commit 3f4cf94

Please sign in to comment.