blob: 003f23af7b8a32942b76f2b152b716e492d7578b [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Asim Shankarae8d4c52014-10-08 13:03:31 -07005package security
6
7import (
8 "crypto/ecdsa"
Asim Shankarae8d4c52014-10-08 13:03:31 -07009 "os"
10 "path"
11
Jiri Simsa6ac95222015-02-23 16:11:49 -080012 "v.io/v23/security"
Mike Burrows7f7088d2015-03-25 13:05:00 -070013 "v.io/v23/verror"
14)
15
Todd Wangb3511492015-04-07 23:32:34 -070016const pkgPath = "v.io/x/ref/lib/security"
Mike Burrows7f7088d2015-03-25 13:05:00 -070017
18var (
19 errCantCreateSigner = verror.Register(pkgPath+".errCantCreateSigner", verror.NoRetry, "{1:}{2:} failed to create serialization.Signer{:_}")
20 errCantLoadBlessingRoots = verror.Register(pkgPath+".errCantLoadBlessingRoots", verror.NoRetry, "{1:}{2:} failed to load BlessingRoots{:_}")
21 errCantLoadBlessingStore = verror.Register(pkgPath+".errCantLoadBlessingStore", verror.NoRetry, "{1:}{2:} failed to load BlessingStore{:_}")
22 errCantInitPrivateKey = verror.Register(pkgPath+".errCantInitPrivateKey", verror.NoRetry, "{1:}{2:} failed to initialize private key{:_}")
23 errNotADirectory = verror.Register(pkgPath+".errNotADirectory", verror.NoRetry, "{1:}{2:} {3} is not a directory{:_}")
24 errCantCreate = verror.Register(pkgPath+".errCantCreate", verror.NoRetry, "{1:}{2:} failed to create {3}{:_}")
25 errCantOpenForWriting = verror.Register(pkgPath+".errCantOpenForWriting", verror.NoRetry, "{1:}{2:} failed to open {3} for writing{:_}")
26 errCantGenerateKey = verror.Register(pkgPath+".errCantGenerateKey", verror.NoRetry, "{1:}{2:} failed to generate private key{:_}")
27 errCantSaveKey = verror.Register(pkgPath+".errCantSaveKey", verror.NoRetry, "{1:}{2:} failed to save private key to {3}{:_}")
Asim Shankarae8d4c52014-10-08 13:03:31 -070028)
29
gauthamt1e313bc2014-11-10 15:45:56 -080030const (
31 blessingStoreDataFile = "blessingstore.data"
32 blessingStoreSigFile = "blessingstore.sig"
33
34 blessingRootsDataFile = "blessingroots.data"
35 blessingRootsSigFile = "blessingroots.sig"
36
37 privateKeyFile = "privatekey.pem"
38)
Asim Shankarae8d4c52014-10-08 13:03:31 -070039
Asim Shankarae8d4c52014-10-08 13:03:31 -070040// NewPrincipal mints a new private key and generates a principal based on
41// this key, storing its BlessingRoots and BlessingStore in memory.
42func NewPrincipal() (security.Principal, error) {
gauthamta134eda2014-11-05 17:57:42 -080043 pub, priv, err := NewPrincipalKey()
Asim Shankarae8d4c52014-10-08 13:03:31 -070044 if err != nil {
45 return nil, err
46 }
47 return security.CreatePrincipal(security.NewInMemoryECDSASigner(priv), newInMemoryBlessingStore(pub), newInMemoryBlessingRoots())
48}
49
gauthamt98108162014-11-11 18:45:56 -080050// PrincipalStateSerializer is used to persist BlessingRoots/BlessingStore state for
51// a principal with the provided SerializerReaderWriters.
52type PrincipalStateSerializer struct {
53 BlessingRoots SerializerReaderWriter
54 BlessingStore SerializerReaderWriter
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -070055}
56
gauthamt98108162014-11-11 18:45:56 -080057// NewPrincipalStateSerializer is a convenience function that returns a serializer
58// for BlessingStore and BlessingRoots given a directory location. We create the
59// directory if it does not already exist.
60func NewPrincipalStateSerializer(dir string) (*PrincipalStateSerializer, error) {
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -070061 if err := mkDir(dir); err != nil {
62 return nil, err
63 }
gauthamt98108162014-11-11 18:45:56 -080064 return &PrincipalStateSerializer{
Ankur27c56fd2014-11-17 19:30:34 -080065 BlessingRoots: NewFileSerializer(path.Join(dir, blessingRootsDataFile), path.Join(dir, blessingRootsSigFile)),
66 BlessingStore: NewFileSerializer(path.Join(dir, blessingStoreDataFile), path.Join(dir, blessingStoreSigFile)),
gauthamt98108162014-11-11 18:45:56 -080067 }, nil
68}
69
70// NewPrincipalFromSigner creates a new principal using the provided Signer. If previously
71// persisted state is available, we use the serializers to populate BlessingRoots/BlessingStore
72// for the Principal. If provided, changes to the state are persisted and committed with the
73// same serializers. Otherwise, the state (ie: BlessingStore, BlessingRoots) is kept in memory.
74func NewPrincipalFromSigner(signer security.Signer, state *PrincipalStateSerializer) (security.Principal, error) {
75 if state == nil {
76 return security.CreatePrincipal(signer, newInMemoryBlessingStore(signer.PublicKey()), newInMemoryBlessingRoots())
77 }
78 serializationSigner, err := security.CreatePrincipal(signer, nil, nil)
79 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -070080 return nil, verror.New(errCantCreateSigner, nil, err)
gauthamt98108162014-11-11 18:45:56 -080081 }
82 blessingRoots, err := newPersistingBlessingRoots(state.BlessingRoots, serializationSigner)
83 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -070084 return nil, verror.New(errCantLoadBlessingRoots, nil, err)
gauthamt98108162014-11-11 18:45:56 -080085 }
86 blessingStore, err := newPersistingBlessingStore(state.BlessingStore, serializationSigner)
87 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -070088 return nil, verror.New(errCantLoadBlessingStore, nil, err)
gauthamt98108162014-11-11 18:45:56 -080089 }
90 return security.CreatePrincipal(signer, blessingStore, blessingRoots)
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -070091}
92
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -070093// LoadPersistentPrincipal reads state for a principal (private key, BlessingRoots, BlessingStore)
Asim Shankarae8d4c52014-10-08 13:03:31 -070094// from the provided directory 'dir' and commits all state changes to the same directory.
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -070095// If private key file does not exist then an error 'err' is returned such that os.IsNotExist(err) is true.
Mike Burrows7f7088d2015-03-25 13:05:00 -070096// If private key file exists then 'passphrase' must be correct, otherwise ErrBadPassphrase will be returned.
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -070097func LoadPersistentPrincipal(dir string, passphrase []byte) (security.Principal, error) {
98 key, err := loadKeyFromDir(dir, passphrase)
99 if err != nil {
100 return nil, err
101 }
gauthamt98108162014-11-11 18:45:56 -0800102 state, err := NewPrincipalStateSerializer(dir)
103 if err != nil {
104 return nil, err
105 }
106 return NewPrincipalFromSigner(security.NewInMemoryECDSASigner(key), state)
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700107}
108
Ankur4704f5f2014-10-23 12:40:54 -0700109// CreatePersistentPrincipal creates a new principal (private key, BlessingRoots,
110// BlessingStore) and commits all state changes to the provided directory.
111//
112// The generated private key is serialized and saved encrypted if the 'passphrase'
113// is non-nil, and unencrypted otherwise.
114//
115// If the directory has any preexisting principal data, CreatePersistentPrincipal
116// will return an error.
117//
118// The specified directory may not exist, in which case it gets created by this
119// function.
120func CreatePersistentPrincipal(dir string, passphrase []byte) (principal security.Principal, err error) {
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -0700121 if err := mkDir(dir); err != nil {
122 return nil, err
Asim Shankarae8d4c52014-10-08 13:03:31 -0700123 }
Suharsh Sivakumar4e091882014-11-11 11:50:28 -0800124 key, err := initKey(dir, passphrase)
Asim Shankarae8d4c52014-10-08 13:03:31 -0700125 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700126 return nil, verror.New(errCantInitPrivateKey, nil, err)
Asim Shankarae8d4c52014-10-08 13:03:31 -0700127 }
gauthamt98108162014-11-11 18:45:56 -0800128 state, err := NewPrincipalStateSerializer(dir)
129 if err != nil {
130 return nil, err
131 }
132 return NewPrincipalFromSigner(security.NewInMemoryECDSASigner(key), state)
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -0700133}
134
Ankurc24ff422014-12-16 17:59:26 -0800135// SetDefaultBlessings sets the provided blessings as default and shareable with
136// all peers on provided principal's BlessingStore, and also adds it as a root to
137// the principal's BlessingRoots.
138func SetDefaultBlessings(p security.Principal, blessings security.Blessings) error {
139 if err := p.BlessingStore().SetDefault(blessings); err != nil {
140 return err
141 }
142 if _, err := p.BlessingStore().Set(blessings, security.AllPrincipals); err != nil {
143 return err
144 }
145 if err := p.AddToRoots(blessings); err != nil {
146 return err
147 }
148 return nil
149}
150
Suharsh Sivakumar8a7fba42014-10-27 12:40:48 -0700151// InitDefaultBlessings uses the provided principal to create a self blessing for name 'name',
152// sets it as default on the principal's BlessingStore and adds it as root to the principal's BlessingRoots.
Ankurc24ff422014-12-16 17:59:26 -0800153// TODO(ataly): Get rid this function given that we have SetDefaultBlessings.
Suharsh Sivakumar8a7fba42014-10-27 12:40:48 -0700154func InitDefaultBlessings(p security.Principal, name string) error {
155 blessing, err := p.BlessSelf(name)
156 if err != nil {
157 return err
158 }
Ankurc24ff422014-12-16 17:59:26 -0800159 return SetDefaultBlessings(p, blessing)
Suharsh Sivakumar8a7fba42014-10-27 12:40:48 -0700160}
161
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -0700162func mkDir(dir string) error {
163 if finfo, err := os.Stat(dir); err == nil {
164 if !finfo.IsDir() {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700165 return verror.New(errNotADirectory, nil, dir)
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -0700166 }
167 } else if err := os.MkdirAll(dir, 0700); err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700168 return verror.New(errCantCreate, nil, dir, err)
Srdjan Petrovicf07f4a02014-10-22 16:31:06 -0700169 }
170 return nil
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700171}
172
173func loadKeyFromDir(dir string, passphrase []byte) (*ecdsa.PrivateKey, error) {
174 keyFile := path.Join(dir, privateKeyFile)
175 f, err := os.Open(keyFile)
176 if err != nil {
177 return nil, err
178 }
179 defer f.Close()
Ankur73e7a932014-10-24 15:57:03 -0700180 key, err := LoadPEMKey(f, passphrase)
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700181 if err != nil {
182 return nil, err
183 }
184 return key.(*ecdsa.PrivateKey), nil
185}
186
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700187func initKey(dir string, passphrase []byte) (*ecdsa.PrivateKey, error) {
Asim Shankarae8d4c52014-10-08 13:03:31 -0700188 keyFile := path.Join(dir, privateKeyFile)
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700189 f, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
Asim Shankarae8d4c52014-10-08 13:03:31 -0700190 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700191 return nil, verror.New(errCantOpenForWriting, nil, keyFile, err)
Asim Shankarae8d4c52014-10-08 13:03:31 -0700192 }
193 defer f.Close()
gauthamta134eda2014-11-05 17:57:42 -0800194 _, key, err := NewPrincipalKey()
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700195 if err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700196 return nil, verror.New(errCantGenerateKey, nil, err)
Asim Shankarae8d4c52014-10-08 13:03:31 -0700197 }
Ankur73e7a932014-10-24 15:57:03 -0700198 if err := SavePEMKey(f, key, passphrase); err != nil {
Mike Burrows7f7088d2015-03-25 13:05:00 -0700199 return nil, verror.New(errCantSaveKey, nil, keyFile, err)
Suharsh Sivakumaraca1c322014-10-21 11:27:32 -0700200 }
201 return key, nil
Asim Shankarae8d4c52014-10-08 13:03:31 -0700202}