diff --git a/README.md b/README.md index f31a80e2..56bc3548 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ share Generate URL for sharing. cp Copy files and objects. mirror Mirror buckets and folders. find Finds files which match the given set of parameters. +stat Stat contents of objects and folders. diff List objects with size difference or missing between two folders or buckets. rm Remove files and objects. events Manage object notifications. diff --git a/cmd/cat-main.go b/cmd/cat-main.go index 3c4eee6e..3a1fa491 100644 --- a/cmd/cat-main.go +++ b/cmd/cat-main.go @@ -34,7 +34,12 @@ import ( ) var ( - catFlags = []cli.Flag{} + catFlags = []cli.Flag{ + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Decrypt object (using server-side encryption)", + }, + } ) // Display contents of a file. @@ -53,6 +58,9 @@ USAGE: FLAGS: {{range .VisibleFlags}}{{.}} {{end}} + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values EXAMPLES: 1. Stream an object from Amazon S3 cloud storage to mplayer standard input. $ {{.HelpName}} s3/ferenginar/klingon_opera_aktuh_maylotah.ogg | mplayer - @@ -62,7 +70,9 @@ EXAMPLES: 3. Concatenate multiple files to one. $ {{.HelpName}} part.* > complete.img - + + 4. Stream a server encrypted object from Amazon S3 cloud storage to standard output. + $ {{.HelpName}} --encrypt-key 's3/ferenginar=32byteslongsecretkeymustbegiven1' s3/ferenginar/klingon_opera_aktuh_maylotah.ogg `, } @@ -129,7 +139,7 @@ func checkCatSyntax(ctx *cli.Context) { } // catURL displays contents of a URL to stdout. -func catURL(sourceURL string) *probe.Error { +func catURL(sourceURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { var reader io.Reader size := int64(-1) switch sourceURL { @@ -146,7 +156,7 @@ func catURL(sourceURL string) *probe.Error { if err == nil && client.GetURL().Type == objectStorage { size = content.Size } - if reader, err = getSourceStreamFromURL(sourceURL); err != nil { + if reader, err = getSourceStreamFromURL(sourceURL, encKeyDB); err != nil { return err.Trace(sourceURL) } } @@ -227,10 +237,16 @@ func mainCat(ctx *cli.Context) error { } } } + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } + encKeyDB, err := parseEncryptionKeys(sseKeys) + fatalIf(err, "Unable to parse encryption keys") // Convert arguments to URLs: expand alias, fix format. for _, url := range args { - fatalIf(catURL(url).Trace(url), "Unable to read from `"+url+"`.") + fatalIf(catURL(url, encKeyDB).Trace(url), "Unable to read from `"+url+"`.") } return nil } diff --git a/cmd/client-fs.go b/cmd/client-fs.go index 98992e92..f4ef2ec2 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -315,7 +315,7 @@ func (f *fsClient) put(reader io.Reader, size int64, metadata map[string][]strin } // Put - create a new file with metadata. -func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader) (int64, *probe.Error) { +func (f *fsClient) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (int64, *probe.Error) { return f.put(reader, size, nil, progress) } @@ -368,7 +368,7 @@ func createFile(fpath string) (io.WriteCloser, error) { } // Copy - copy data from source to destination -func (f *fsClient) Copy(source string, size int64, progress io.Reader) *probe.Error { +func (f *fsClient) Copy(source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error { // Don't use f.Get() f.Put() directly. Instead use readFile and createFile destination := f.PathURL.Path if destination == source { // Cannot copy file into itself @@ -434,7 +434,7 @@ func (f *fsClient) get() (io.Reader, *probe.Error) { } // Get returns reader and any additional metadata. -func (f *fsClient) Get() (io.Reader, *probe.Error) { +func (f *fsClient) Get(sseKey string) (io.Reader, *probe.Error) { return f.get() } @@ -968,7 +968,7 @@ func (f *fsClient) SetAccess(access string) *probe.Error { } // Stat - get metadata from path. -func (f *fsClient) Stat(isIncomplete, isFetchMeta bool) (content *clientContent, err *probe.Error) { +func (f *fsClient) Stat(isIncomplete, isFetchMeta bool, sseKey string) (content *clientContent, err *probe.Error) { st, err := f.fsStat(isIncomplete) if err != nil { return nil, err.Trace(f.PathURL.String()) diff --git a/cmd/client-fs_test.go b/cmd/client-fs_test.go index 2fc30a27..4f7b2910 100644 --- a/cmd/client-fs_test.go +++ b/cmd/client-fs_test.go @@ -45,7 +45,7 @@ func (s *TestSuite) TestList(c *C) { var n int64 n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) @@ -56,7 +56,7 @@ func (s *TestSuite) TestList(c *C) { reader = bytes.NewReader([]byte(data)) n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) @@ -84,7 +84,7 @@ func (s *TestSuite) TestList(c *C) { reader = bytes.NewReader([]byte(data)) n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) @@ -144,7 +144,7 @@ func (s *TestSuite) TestList(c *C) { reader = bytes.NewReader([]byte(data)) n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) @@ -210,7 +210,7 @@ func (s *TestSuite) TestStatBucket(c *C) { c.Assert(err, IsNil) err = fsClient.MakeBucket("us-east-1", true) c.Assert(err, IsNil) - _, err = fsClient.Stat(false, false) + _, err = fsClient.Stat(false, false, "") c.Assert(err, IsNil) } @@ -251,7 +251,7 @@ func (s *TestSuite) TestPut(c *C) { var n int64 n, err = fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) } @@ -271,11 +271,11 @@ func (s *TestSuite) TestGet(c *C) { reader = bytes.NewReader([]byte(data)) n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - reader, err = fsClient.Get() + reader, err = fsClient.Get("") c.Assert(err, IsNil) var results bytes.Buffer _, e = io.Copy(&results, reader) @@ -299,11 +299,11 @@ func (s *TestSuite) TestGetRange(c *C) { reader = bytes.NewReader([]byte(data)) n, err := fsClient.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - reader, err = fsClient.Get() + reader, err = fsClient.Get("") c.Assert(err, IsNil) var results bytes.Buffer buf := make([]byte, 5) @@ -330,11 +330,11 @@ func (s *TestSuite) TestStatObject(c *C) { reader := bytes.NewReader([]byte(data)) n, err := fsClient.Put(context.Background(), reader, int64(dataLen), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - content, err := fsClient.Stat(false, false) + content, err := fsClient.Stat(false, false, "") c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(dataLen)) } @@ -356,10 +356,10 @@ func (s *TestSuite) TestCopy(c *C) { reader = bytes.NewReader([]byte(data)) n, err := fsClientSource.Put(context.Background(), reader, int64(len(data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil) + err = fsClientTarget.Copy(sourcePath, int64(len(data)), nil, "", "") c.Assert(err, IsNil) } diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 76d15d1f..92a5df24 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -19,6 +19,7 @@ package cmd import ( "context" "crypto/tls" + "encoding/base64" "hash/fnv" "io" "net" @@ -506,9 +507,16 @@ func (c *s3Client) Watch(params watchParams) (*watchObject, *probe.Error) { } // Get - get object with metadata. -func (c *s3Client) Get() (io.Reader, *probe.Error) { +func (c *s3Client) Get(sseKey string) (io.Reader, *probe.Error) { bucket, object := c.url2BucketAndObject() - reader, e := c.api.GetObject(bucket, object, minio.GetObjectOptions{}) + var opts minio.GetObjectOptions + if sseKey != "" { + key := minio.NewSSEInfo([]byte(sseKey), "AES256") + for k, v := range key.GetSSEHeaders() { + opts.Set(k, v) + } + } + reader, e := c.api.GetObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "NoSuchBucket" { @@ -530,7 +538,7 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) { } // Copy - copy object -func (c *s3Client) Copy(source string, size int64, progress io.Reader) *probe.Error { +func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error { dstBucket, dstObject := c.url2BucketAndObject() if dstBucket == "" { return probe.NewError(BucketNameEmpty{}) @@ -538,11 +546,21 @@ func (c *s3Client) Copy(source string, size int64, progress io.Reader) *probe.Er tokens := splitStr(source, string(c.targetURL.Separator), 3) + var srcKeyPtr, tgtKeyPtr *minio.SSEInfo + if srcSSEKey != "" { + srcKey := minio.NewSSEInfo([]byte(srcSSEKey), "AES256") + srcKeyPtr = &srcKey + } + if tgtSSEKey != "" { + tgtKey := minio.NewSSEInfo([]byte(tgtSSEKey), "AES256") + tgtKeyPtr = &tgtKey + } + // Source object - src := minio.NewSourceInfo(tokens[1], tokens[2], nil) + src := minio.NewSourceInfo(tokens[1], tokens[2], srcKeyPtr) // Destination object - dst, e := minio.NewDestinationInfo(dstBucket, dstObject, nil, nil) + dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtKeyPtr, nil) if e != nil { return probe.NewError(e) } @@ -578,7 +596,7 @@ func (c *s3Client) Copy(source string, size int64, progress io.Reader) *probe.Er } // Put - upload an object with custom metadata. -func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader) (int64, *probe.Error) { +func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (int64, *probe.Error) { bucket, object := c.url2BucketAndObject() contentType, ok := metadata["Content-Type"] if ok { @@ -612,6 +630,11 @@ func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metada if ok { delete(metadata, "X-Amz-Storage-Class") } + if sseKey != "" { + metadata["x-amz-server-side-encryption-customer-algorithm"] = "AES256" + metadata["x-amz-server-side-encryption-customer-key"] = base64.StdEncoding.EncodeToString([]byte(sseKey)) + metadata["x-amz-server-side-encryption-customer-key-MD5"] = sumMD5Base64([]byte(sseKey)) + } if bucket == "" { return 0, probe.NewError(BucketNameEmpty{}) } @@ -859,7 +882,7 @@ func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, do } // Stat - send a 'HEAD' on a bucket or object to fetch its metadata. -func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe.Error) { +func (c *s3Client) Stat(isIncomplete, isFetchMeta bool, sseKey string) (*clientContent, *probe.Error) { c.mutex.Lock() defer c.mutex.Unlock() bucket, object := c.url2BucketAndObject() @@ -915,7 +938,12 @@ func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe. } return nil, probe.NewError(ObjectMissing{}) } - + opts := minio.StatObjectOptions{} + if sseKey != "" { + opts.Set("x-amz-server-side-encryption-customer-algorithm", "AES256") + opts.Set("x-amz-server-side-encryption-customer-key", base64.StdEncoding.EncodeToString([]byte(sseKey))) + opts.Set("x-amz-server-side-encryption-customer-key-MD5", sumMD5Base64([]byte(sseKey))) + } for objectStat := range c.listObjectWrapper(bucket, object, nonRecursive, nil) { if objectStat.Err != nil { return nil, probe.NewError(objectStat.Err) @@ -929,7 +957,7 @@ func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe. objectMetadata.Metadata = map[string]string{} objectMetadata.EncryptionHeaders = map[string]string{} if isFetchMeta { - stat, err := c.getObjectStat(bucket, object) + stat, err := c.getObjectStat(bucket, object, opts) if err != nil { return nil, err } @@ -944,7 +972,7 @@ func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe. objectMetadata.Type = os.ModeDir if isFetchMeta { - stat, err := c.getObjectStat(bucket, object) + stat, err := c.getObjectStat(bucket, object, opts) if err != nil { return nil, err } @@ -955,14 +983,13 @@ func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe. return objectMetadata, nil } } - return c.getObjectStat(bucket, object) + return c.getObjectStat(bucket, object, opts) } // getObjectStat returns the metadata of an object from a HEAD call. -func (c *s3Client) getObjectStat(bucket, object string) (*clientContent, *probe.Error) { +func (c *s3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*clientContent, *probe.Error) { objectMetadata := &clientContent{} - - objectStat, e := c.api.StatObject(bucket, object, minio.StatObjectOptions{}) + objectStat, e := c.api.StatObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { @@ -1342,7 +1369,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutineDirOpt(contentCh chan *client } else if strings.HasSuffix(object, string(c.targetURL.Separator)) { // Get stat of given object is a directory. isIncomplete := true - content, perr := c.Stat(isIncomplete, false) + content, perr := c.Stat(isIncomplete, false, "") cContent = content if perr != nil { contentCh <- &clientContent{URL: *c.targetURL, Err: perr} @@ -1496,7 +1523,7 @@ func (c *s3Client) listRecursiveInRoutineDirOpt(contentCh chan *clientContent, d // Get stat of given object is a directory. isIncomplete := false isFetchMeta := false - content, perr := c.Stat(isIncomplete, isFetchMeta) + content, perr := c.Stat(isIncomplete, isFetchMeta, "") cContent = content if perr != nil { contentCh <- &clientContent{URL: *c.targetURL, Err: perr} diff --git a/cmd/client-s3_test.go b/cmd/client-s3_test.go index f33cd443..39d047d9 100644 --- a/cmd/client-s3_test.go +++ b/cmd/client-s3_test.go @@ -222,11 +222,11 @@ func (s *TestSuite) TestObjectOperations(c *C) { reader = bytes.NewReader(object.data) n, err := s3c.Put(context.Background(), reader, int64(len(object.data)), map[string]string{ "Content-Type": "application/octet-stream", - }, nil) + }, nil, "") c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(object.data))) - reader, err = s3c.Get() + reader, err = s3c.Get("") c.Assert(err, IsNil) var buffer bytes.Buffer { diff --git a/cmd/client-url.go b/cmd/client-url.go index c8824f9c..1b8d835f 100644 --- a/cmd/client-url.go +++ b/cmd/client-url.go @@ -172,16 +172,19 @@ func urlJoinPath(url1, url2 string) string { // url2Stat returns stat info for URL. func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) { - return url2StatWithMetadata(urlStr, false) + return url2StatWithMetadata(urlStr, false, nil) } // url2Stat returns stat info for URL. -func url2StatWithMetadata(urlStr string, isFetchMeta bool) (client Client, content *clientContent, err *probe.Error) { +func url2StatWithMetadata(urlStr string, isFetchMeta bool, encKeyDB map[string][]prefixSSEPair) (client Client, content *clientContent, err *probe.Error) { client, err = newClient(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } - content, err = client.Stat(false, isFetchMeta) + alias, _ := url2Alias(urlStr) + sseKey := getSSEKey(urlStr, encKeyDB[alias]) + + content, err = client.Stat(false, isFetchMeta, sseKey) if err != nil { return nil, nil, err.Trace(urlStr) } diff --git a/cmd/client.go b/cmd/client.go index 101d1e57..dabd5bf0 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -44,7 +44,7 @@ const defaultMultipartThreadsNum = 4 // Client - client interface type Client interface { // Common operations - Stat(isIncomplete, isFetchMeta bool) (content *clientContent, err *probe.Error) + Stat(isIncomplete, isFetchMeta bool, sseKey string) (content *clientContent, err *probe.Error) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent // Bucket operations @@ -56,11 +56,11 @@ type Client interface { SetAccess(access string) *probe.Error // I/O operations - Copy(source string, size int64, progress io.Reader) *probe.Error + Copy(source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error // I/O operations with metadata. - Get() (reader io.Reader, err *probe.Error) - Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader) (n int64, err *probe.Error) + Get(sseKey string) (reader io.Reader, err *probe.Error) + Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (n int64, err *probe.Error) // I/O operations with expiration ShareDownload(expires time.Duration) (string, *probe.Error) diff --git a/cmd/common-methods.go b/cmd/common-methods.go index db1f24a4..a3f6ec27 100644 --- a/cmd/common-methods.go +++ b/cmd/common-methods.go @@ -67,28 +67,29 @@ func isAliasURLDir(aliasURL string) bool { } // getSourceStreamFromURL gets a reader from URL. -func getSourceStreamFromURL(urlStr string) (reader io.Reader, err *probe.Error) { +func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.Reader, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, err.Trace(urlStr) } - reader, _, err = getSourceStream(alias, urlStrFull, false) + sseKey := getSSEKey(urlStr, encKeyDB[alias]) + reader, _, err = getSourceStream(alias, urlStrFull, false, sseKey) return reader, err } // getSourceStream gets a reader from URL. -func getSourceStream(alias string, urlStr string, fetchStat bool) (reader io.Reader, metadata map[string]string, err *probe.Error) { +func getSourceStream(alias string, urlStr string, fetchStat bool, sseKey string) (reader io.Reader, metadata map[string]string, err *probe.Error) { sourceClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return nil, nil, err.Trace(alias, urlStr) } - reader, err = sourceClnt.Get() + reader, err = sourceClnt.Get(sseKey) if err != nil { return nil, nil, err.Trace(alias, urlStr) } metadata = map[string]string{} if fetchStat { - st, err := sourceClnt.Stat(false, true) + st, err := sourceClnt.Stat(false, true, sseKey) if err != nil { return nil, nil, err.Trace(alias, urlStr) } @@ -103,12 +104,12 @@ func getSourceStream(alias string, urlStr string, fetchStat bool) (reader io.Rea } // putTargetStream writes to URL from Reader. -func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader) (int64, *probe.Error) { +func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sseKey string) (int64, *probe.Error) { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return 0, err.Trace(alias, urlStr) } - n, err := targetClnt.Put(ctx, reader, size, metadata, progress) + n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sseKey) if err != nil { return n, err.Trace(alias, urlStr) } @@ -116,7 +117,7 @@ func putTargetStream(ctx context.Context, alias string, urlStr string, reader io } // putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF. -func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64) (int64, *probe.Error) { +func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sseKey string) (int64, *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return 0, err.Trace(alias, urlStr) @@ -125,16 +126,16 @@ func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64) (int64, metadata := map[string]string{ "Content-Type": contentType, } - return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil) + return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sseKey) } // copySourceToTargetURL copies to targetURL from source. -func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader) *probe.Error { +func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSEKey, tgtSSEKey string) *probe.Error { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return err.Trace(alias, urlStr) } - err = targetClnt.Copy(source, size, progress) + err = targetClnt.Copy(source, size, progress, srcSSEKey, tgtSSEKey) if err != nil { return err.Trace(alias, urlStr) } @@ -150,17 +151,16 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader) targetAlias := urls.TargetAlias targetURL := urls.TargetContent.URL length := urls.SourceContent.Size - // Optimize for server side copy if the host is same. if sourceAlias == targetAlias { sourcePath := filepath.ToSlash(sourceURL.Path) - err := copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress) + err := copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, urls.SrcSSEKey, urls.TgtSSEKey) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } } else { // Proceed with regular stream copy. - reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true) + reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, urls.SrcSSEKey) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } @@ -170,7 +170,12 @@ func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader) metadata[k] = v } } - _, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress) + if urls.SrcSSEKey != "" { + delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm") + delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5") + } + + _, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, urls.TgtSSEKey) if err != nil { return urls.WithError(err.Trace(targetURL.String())) } diff --git a/cmd/config-host-add.go b/cmd/config-host-add.go index 679d8b36..47359a3b 100644 --- a/cmd/config-host-add.go +++ b/cmd/config-host-add.go @@ -164,7 +164,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) { return "", err } - if _, err = s3Client.Stat(false, false); err != nil { + if _, err = s3Client.Stat(false, false, ""); err != nil { switch err.ToGoError().(type) { case BucketDoesNotExist: // Bucket doesn't exist, means signature probing worked V4. @@ -175,7 +175,7 @@ func probeS3Signature(accessKey, secretKey, url string) (string, *probe.Error) { if err != nil { return "", err } - if _, err = s3Client.Stat(false, false); err != nil { + if _, err = s3Client.Stat(false, false, ""); err != nil { switch err.ToGoError().(type) { case BucketDoesNotExist: // Bucket doesn't exist, means signature probing worked with V2. diff --git a/cmd/cp-main.go b/cmd/cp-main.go index f22b79d4..0dd94670 100644 --- a/cmd/cp-main.go +++ b/cmd/cp-main.go @@ -53,6 +53,10 @@ var ( Name: "storage-class, sc", Usage: "Set storage class for object", }, + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Encrypt/Decrypt objects (using server-side encryption)", + }, } ) @@ -73,6 +77,9 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + EXAMPLES: 1. Copy a list of objects from local file system to Amazon S3 cloud storage. $ {{.HelpName}} Music/*.ogg s3/jukebox/ @@ -98,6 +105,9 @@ EXAMPLES: 8. Copy a local folder with space separated characters to Amazon S3 cloud storage. $ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud + 10. Copy a folder with encrypted objects recursively from Amazon S3 to Minio cloud storage. + $ {{.HelpName}} --recursive --encrypt-key "s3/documents/a/b/c=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2" 's3/documents/' myminio/documents/ + `, } @@ -210,7 +220,9 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex olderThan := session.Header.CommandIntFlags["older-than"] newerThan := session.Header.CommandIntFlags["newer-than"] - + encryptKeys := session.Header.CommandStringFlags["encrypt-key"] + encKeyDB, err := parseEncryptionKeys(encryptKeys) + fatalIf(err, "Unable to parse encryption keys") // Create a session data file to store the processed URLs. dataFP := session.NewDataWriter() @@ -218,8 +230,7 @@ func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy contex if !globalQuiet && !globalJSON { // set up progress bar scanBar = scanBarFactory() } - - URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive) + URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB) done := false for !done { select { @@ -420,6 +431,10 @@ func mainCopy(ctx *cli.Context) error { olderThan := ctx.Int("older-than") newerThan := ctx.Int("newer-than") storageClass := ctx.String("storage-class") + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } session := newSessionV8() session.Header.CommandType = "cp" @@ -427,6 +442,7 @@ func mainCopy(ctx *cli.Context) error { session.Header.CommandIntFlags["older-than"] = olderThan session.Header.CommandIntFlags["newer-than"] = newerThan session.Header.CommandStringFlags["storage-class"] = storageClass + session.Header.CommandStringFlags["encrypt-key"] = sseKeys var e error if session.Header.RootPath, e = os.Getwd(); e != nil { diff --git a/cmd/cp-url.go b/cmd/cp-url.go index 665884a0..3236ef53 100644 --- a/cmd/cp-url.go +++ b/cmd/cp-url.go @@ -82,7 +82,7 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) ( // SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f) // prepareCopyURLsTypeA - prepares target and source clientURLs for copying. -func prepareCopyURLsTypeA(sourceURL string, targetURL string) URLs { +func prepareCopyURLsTypeA(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) // Find alias and expanded clientURL. @@ -103,22 +103,32 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) URLs { } // All OK.. We can proceed. Type A - return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB) } // prepareCopyContentTypeA - makes CopyURLs content for copying. -func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) URLs { +func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { + targetContent := clientContent{URL: *newClientURL(targetURL)} + + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceContent.URL.Path)) + targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetContent.URL.Path)) + + srcSSEKey := getSSEKey(sourcePath, encKeyDB[sourceAlias]) + tgtSSEKey := getSSEKey(targetPath, encKeyDB[targetAlias]) + return URLs{ SourceAlias: sourceAlias, SourceContent: sourceContent, TargetAlias: targetAlias, - TargetContent: &clientContent{URL: *newClientURL(targetURL)}, + TargetContent: &targetContent, + SrcSSEKey: srcSSEKey, + TgtSSEKey: tgtSSEKey, } } // SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A // prepareCopyURLsTypeB - prepares target and source clientURLs for copying. -func prepareCopyURLsTypeB(sourceURL string, targetURL string) URLs { +func prepareCopyURLsTypeB(sourceURL string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) // Find alias and expanded clientURL. @@ -139,25 +149,24 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) URLs { } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL) + return makeCopyContentTypeB(sourceAlias, sourceContent, targetAlias, targetURL, encKeyDB) } // makeCopyContentTypeB - CopyURLs content for copying. -func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) URLs { +func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. targetURLParse := newClientURL(targetURL) targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path))) - return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String()) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String(), encKeyDB) } // SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A // prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying. -func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan URLs { +func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { // Extract alias before fiddling with the clientURL. sourceAlias, _, _ := mustExpandAlias(sourceURL) // Find alias and expanded clientURL. targetAlias, targetURL, _ := mustExpandAlias(targetURL) - copyURLsCh := make(chan URLs) go func(sourceURL, targetURL string, copyURLsCh chan URLs) { defer close(copyURLsCh) @@ -182,14 +191,14 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan } // All OK.. We can proceed. Type B: source is a file, target is a folder and exists. - copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL) + copyURLsCh <- makeCopyContentTypeC(sourceAlias, sourceClient.GetURL(), sourceContent, targetAlias, targetURL, encKeyDB) } }(sourceURL, targetURL, copyURLsCh) return copyURLsCh } // makeCopyContentTypeC - CopyURLs content for copying. -func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) URLs { +func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string, encKeyDB map[string][]prefixSSEPair) URLs { newSourceURL := sourceContent.URL pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator)) newSourceSuffix := filepath.ToSlash(newSourceURL.Path) @@ -198,17 +207,17 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent newSourceSuffix = strings.TrimPrefix(newSourceSuffix, sourcePrefix) } newTargetURL := urlJoinPath(targetURL, newSourceSuffix) - return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL) + return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, newTargetURL, encKeyDB) } // MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B // prepareCopyURLsTypeE - prepares target and source clientURLs for copying. -func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan URLs { +func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { copyURLsCh := make(chan URLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) { defer close(copyURLsCh) for _, sourceURL := range sourceURLs { - for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive) { + for cpURLs := range prepareCopyURLsTypeC(sourceURL, targetURL, isRecursive, encKeyDB) { copyURLsCh <- cpURLs } } @@ -217,30 +226,30 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo } // prepareCopyURLs - prepares target and source clientURLs for copying. -func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan URLs { +func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { copyURLsCh := make(chan URLs) - go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) { + go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs, encKeyDB map[string][]prefixSSEPair) { defer close(copyURLsCh) cpType, err := guessCopyURLType(sourceURLs, targetURL, isRecursive) fatalIf(err.Trace(), "Unable to guess the type of copy operation.") switch cpType { case copyURLsTypeA: - copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL) + copyURLsCh <- prepareCopyURLsTypeA(sourceURLs[0], targetURL, encKeyDB) case copyURLsTypeB: - copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL) + copyURLsCh <- prepareCopyURLsTypeB(sourceURLs[0], targetURL, encKeyDB) case copyURLsTypeC: - for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive) { + for cURLs := range prepareCopyURLsTypeC(sourceURLs[0], targetURL, isRecursive, encKeyDB) { copyURLsCh <- cURLs } case copyURLsTypeD: - for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive) { + for cURLs := range prepareCopyURLsTypeD(sourceURLs, targetURL, isRecursive, encKeyDB) { copyURLsCh <- cURLs } default: copyURLsCh <- URLs{Error: errInvalidArgument().Trace(sourceURLs...)} } - }(sourceURLs, targetURL, copyURLsCh) + }(sourceURLs, targetURL, copyURLsCh, encKeyDB) return copyURLsCh } diff --git a/cmd/find.go b/cmd/find.go index fb6fbb99..58a04dfd 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -448,7 +448,7 @@ func getShareURL(path string) string { clnt, err := newClientFromAlias(targetAlias, targetURLFull) fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.") - content, err := clnt.Stat(false, false) + content, err := clnt.Stat(false, false, "") fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.") // Skip if its a directory. diff --git a/cmd/ls-main.go b/cmd/ls-main.go index 469e5ae9..eed3f56d 100644 --- a/cmd/ls-main.go +++ b/cmd/ls-main.go @@ -132,7 +132,7 @@ func mainList(ctx *cli.Context) error { fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") var st *clientContent - if st, err = clnt.Stat(isIncomplete, false); err != nil { + if st, err = clnt.Stat(isIncomplete, false, ""); err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: // For aliases like ``mc ls s3`` it's acceptable to receive BucketNameEmpty error. diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 46f2072f..e784b4bb 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -82,6 +82,10 @@ var ( Name: "storage-class, sc", Usage: "Set storage class for object", }, + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Encrypt/Decrypt objects (using server-side encryption)", + }, } ) @@ -102,6 +106,9 @@ FLAGS: {{range .VisibleFlags}}{{.}} {{end}} +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + EXAMPLES: 1. Mirror a bucket recursively from Minio cloud storage to a bucket on Amazon S3 cloud storage. $ {{.HelpName}} play/photos/2014 s3/backup-photos @@ -135,6 +142,9 @@ EXAMPLES: 10. Mirror a bucket older than 30 days from Amazon S3 bucket test to a local folder. $ {{.HelpName}} --older-than=30 s3/test ~/test + + 11. Mirror server encrypted objects from Minio cloud storage to a bucket on Amazon S3 cloud storage + $ {{.HelpName}} --encrypt-key "minio/photos=32byteslongsecretkeymustbegiven1,s3/archive=32byteslongsecretkeymustbegiven2" minio/photos/ s3/archive `, } @@ -177,6 +187,7 @@ type mirrorJob struct { storageClass string excludeOptions []string + encKeyDB map[string][]prefixSSEPair } // mirrorMessage container for file mirror messages @@ -216,7 +227,7 @@ func (mj *mirrorJob) doRemove(sURLs URLs) URLs { targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path) // Remove extraneous file on target. - err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0, 0)) + err := probe.NewError(removeSingle(targetWithAlias, isIncomplete, mj.isFake, 0, 0, sURLs.encKeyDB)) return sURLs.WithError(err) } @@ -343,6 +354,9 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance // newClient needs the unexpanded path, newCLientURL needs the expanded path targetAlias, expandedTargetPath, _ := mustExpandAlias(targetPath) targetURL := newClientURL(expandedTargetPath) + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) + srcSSEKey := getSSEKey(sourcePath, mj.encKeyDB[sourceAlias]) + tgtSSEKey := getSSEKey(targetPath, mj.encKeyDB[targetAlias]) if event.Type == EventCreate { // we are checking if a destination file exists now, and if we only @@ -352,6 +366,9 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance SourceContent: &clientContent{URL: *sourceURL}, TargetAlias: targetAlias, TargetContent: &clientContent{URL: *targetURL}, + encKeyDB: mj.encKeyDB, + SrcSSEKey: srcSSEKey, + TgtSSEKey: tgtSSEKey, } if event.Size == 0 { sourceClient, err := newClient(aliasedPath) @@ -360,7 +377,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance mj.statusCh <- mirrorURL.WithError(err) continue } - sourceContent, err := sourceClient.Stat(false, false) + sourceContent, err := sourceClient.Stat(false, false, srcSSEKey) if err != nil { // source doesn't exist anymore mj.statusCh <- mirrorURL.WithError(err) @@ -374,7 +391,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance } shouldQueue := false if !mj.isOverwrite { - _, err = targetClient.Stat(false, false) + _, err = targetClient.Stat(false, false, tgtSSEKey) if err == nil { continue } // doesn't exist @@ -397,7 +414,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance mj.statusCh <- mirrorURL.WithError(err) return } - _, err = targetClient.Stat(false, false) + _, err = targetClient.Stat(false, false, tgtSSEKey) if err == nil { continue } // doesn't exist @@ -417,6 +434,9 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance SourceContent: nil, TargetAlias: targetAlias, TargetContent: &clientContent{URL: *targetURL}, + SrcSSEKey: srcSSEKey, + TgtSSEKey: tgtSSEKey, + encKeyDB: mj.encKeyDB, } mirrorURL.TotalCount = mj.TotalObjects mirrorURL.TotalSize = mj.TotalBytes @@ -460,7 +480,7 @@ func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.Cance parallel, queueCh := newParallelManager(mj.statusCh, mj.status) - URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions) + URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions, mj.encKeyDB) for { select { @@ -565,7 +585,7 @@ func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc } } -func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan int, storageClass string) *mirrorJob { +func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch bool, excludeOptions []string, olderThan, newerThan int, storageClass string, encKeyDB map[string][]prefixSSEPair) *mirrorJob { // we'll define the status to use here, // do we want the quiet status? or the progressbar var status = NewProgressStatus() @@ -590,6 +610,7 @@ func newMirrorJob(srcURL, dstURL string, isFake, isRemove, isOverwrite, isWatch olderThan: olderThan, newerThan: newerThan, storageClass: storageClass, + encKeyDB: encKeyDB, status: status, statusCh: make(chan URLs), queueCh: make(chan func() URLs), @@ -625,7 +646,7 @@ func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error { } // runMirror - mirrors all buckets to another S3 server -func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { +func runMirror(srcURL, dstURL string, ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) *probe.Error { // This is kept for backward compatibility, `--force` means // --overwrite. isOverwrite := ctx.Bool("force") @@ -642,7 +663,8 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { ctx.StringSlice("exclude"), ctx.Int("older-than"), ctx.Int("newer-than"), - ctx.String("storage-class")) + ctx.String("storage-class"), + encKeyDB) srcClt, err := newClient(srcURL) fatalIf(err, "Unable to initialize `"+srcURL+"`") @@ -669,7 +691,6 @@ func runMirror(srcURL, dstURL string, ctx *cli.Context) *probe.Error { } sourceSuffix := strings.TrimPrefix(d.FirstURL, srcClt.GetURL().String()) - newSrcURL := path.Join(srcURL, sourceSuffix) newTgtURL := path.Join(dstURL, sourceSuffix) @@ -728,8 +749,15 @@ func mainMirror(ctx *cli.Context) error { srcURL := args[0] tgtURL := args[1] + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } - if err := runMirror(srcURL, tgtURL, ctx); err != nil { + encKeyDB, err := parseEncryptionKeys(sseKeys) + fatalIf(err, "Unable to parse encryption keys") + + if err := runMirror(srcURL, tgtURL, ctx, encKeyDB); err != nil { errorIf(err.Trace(srcURL, tgtURL), "Unable to mirror") return exitStatus(globalErrorExitStatus) } diff --git a/cmd/mirror-url.go b/cmd/mirror-url.go index c79257af..83aa43b0 100644 --- a/cmd/mirror-url.go +++ b/cmd/mirror-url.go @@ -18,6 +18,7 @@ package cmd import ( "fmt" + "path/filepath" "strings" "github.com/minio/cli" @@ -82,7 +83,7 @@ func matchExcludeOptions(excludeOptions []string, srcSuffix string) bool { return false } -func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, URLsCh chan<- URLs) { +func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, URLsCh chan<- URLs, encKeyDB map[string][]prefixSSEPair) { // source and targets are always directories sourceSeparator := string(newClientURL(sourceURL).Separator) if !strings.HasSuffix(sourceURL, sourceSeparator) { @@ -131,6 +132,11 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov continue } + sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceClnt.GetURL().Path)) + srcSSEKey := getSSEKey(sourcePath, encKeyDB[sourceAlias]) + targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetClnt.GetURL().Path)) + tgtSSEKey := getSSEKey(targetPath, encKeyDB[targetAlias]) + switch diffMsg.Diff { case differInNone: // No difference, continue. @@ -142,6 +148,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov URLsCh <- URLs{Error: errOverWriteNotAllowed(diffMsg.SecondURL)} continue } + sourceSuffix := strings.TrimPrefix(diffMsg.FirstURL, sourceURL) // Either available only in source or size differs and force is set targetPath := urlJoinPath(targetURL, sourceSuffix) @@ -152,6 +159,8 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov SourceContent: sourceContent, TargetAlias: targetAlias, TargetContent: targetContent, + SrcSSEKey: srcSSEKey, + TgtSSEKey: tgtSSEKey, } case differInFirst: // Only in first, always copy. @@ -164,8 +173,11 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov SourceContent: sourceContent, TargetAlias: targetAlias, TargetContent: targetContent, + SrcSSEKey: srcSSEKey, + TgtSSEKey: tgtSSEKey, } case differInSecond: + if !isRemove && !isFake { // Object removal not allowed if --remove is not set. URLsCh <- URLs{ @@ -176,6 +188,7 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov URLsCh <- URLs{ TargetAlias: targetAlias, TargetContent: diffMsg.secondContent, + TgtSSEKey: tgtSSEKey, } default: URLsCh <- URLs{ @@ -186,8 +199,8 @@ func deltaSourceTarget(sourceURL, targetURL string, isFake, isOverwrite, isRemov } // Prepares urls that need to be copied or removed based on requested options. -func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string) <-chan URLs { +func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs { URLsCh := make(chan URLs) - go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh) + go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh, encKeyDB) return URLsCh } diff --git a/cmd/pipe-main.go b/cmd/pipe-main.go index 7e52054f..f1d7cd6d 100644 --- a/cmd/pipe-main.go +++ b/cmd/pipe-main.go @@ -25,7 +25,12 @@ import ( ) var ( - pipeFlags = []cli.Flag{} + pipeFlags = []cli.Flag{ + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Encrypt object (using server-side encryption)", + }, + } ) // Display contents of a file. @@ -44,6 +49,10 @@ USAGE: FLAGS: {{range .VisibleFlags}}{{.}} {{end}} + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + EXAMPLES: 1. Write contents of stdin to a file on local filesystem. $ {{.HelpName}} /tmp/hello-world.go @@ -56,19 +65,25 @@ EXAMPLES: 4. Stream MySQL database dump to Amazon S3 directly. $ mysqldump -u root -p ******* accountsdb | {{.HelpName}} s3/ferenginar/backups/accountsdb-oct-9-2015.sql + + 5. Stream an object to Amazon S3 cloud storage and encrypt on server. + $ {{.HelpName}} --encrypt-key "s3/ferenginar/=32byteslongsecretkeymustbegiven1" s3/ferenginar/klingon_opera_aktuh_maylotah.ogg + `, } -func pipe(targetURL string) *probe.Error { +func pipe(targetURL string, encKeyDB map[string][]prefixSSEPair) *probe.Error { if targetURL == "" { // When no target is specified, pipe cat's stdin to stdout. return catOut(os.Stdin, -1).Trace() } + alias, _ := url2Alias(targetURL) + sseKey := getSSEKey(targetURL, encKeyDB[alias]) // Stream from stdin to multiple objects until EOF. // Ignore size, since os.Stat() would not return proper size all the time // for local filesystem for example /proc files. - _, err := putTargetStreamWithURL(targetURL, os.Stdin, -1) + _, err := putTargetStreamWithURL(targetURL, os.Stdin, -1, sseKey) // TODO: See if this check is necessary. switch e := err.ToGoError().(type) { case *os.PathError: @@ -94,12 +109,19 @@ func mainPipe(ctx *cli.Context) error { checkPipeSyntax(ctx) if len(ctx.Args()) == 0 { - err := pipe("") + err := pipe("", nil) fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.") } else { // extract URLs. URLs := ctx.Args() - err := pipe(URLs[0]) + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } + + encKeyDB, err := parseEncryptionKeys(sseKeys) + fatalIf(err, "Unable to parse encryption keys") + err = pipe(URLs[0], encKeyDB) fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.") } diff --git a/cmd/rm-main.go b/cmd/rm-main.go index acbfcd52..f28bb829 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -69,6 +69,10 @@ var ( Name: "newer-than", Usage: "Remove objects newer than N days", }, + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Encrypt object (using server-side encryption)", + }, } ) @@ -88,6 +92,10 @@ USAGE: FLAGS: {{range .VisibleFlags}}{{.}} {{end}} + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + EXAMPLES: 1. Remove a file. $ {{.HelpName}} 1999/old-backup.tgz @@ -113,6 +121,9 @@ EXAMPLES: 8. Drop all incomplete uploads on 'jazz-songs' bucket. $ {{.HelpName}} --incomplete --recursive s3/jazz-songs/ + 9. Remove an encrypted object from s3. + $ {{.HelpName}} --encrypt-key "s3/ferenginar/=32byteslongsecretkeymustbegiven1" s3/ferenginar/1999/old-backup.tgz + `, } @@ -173,7 +184,7 @@ func checkRmSyntax(ctx *cli.Context) { } } -func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int) error { +func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int, encKeyDB map[string][]prefixSSEPair) error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -181,7 +192,9 @@ func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, new return exitStatus(globalErrorExitStatus) // End of journey. } isFetchMeta := true - content, pErr := clnt.Stat(isIncomplete, isFetchMeta) + alias, _ := url2Alias(url) + sseKey := getSSEKey(url, encKeyDB[alias]) + content, pErr := clnt.Stat(isIncomplete, isFetchMeta, sseKey) if pErr != nil { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") return exitStatus(globalErrorExitStatus) @@ -223,7 +236,7 @@ func removeSingle(url string, isIncomplete bool, isFake bool, olderThan int, new return nil } -func removeRecursive(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int) error { +func removeRecursive(url string, isIncomplete bool, isFake bool, olderThan int, newerThan int, encKeyDB map[string][]prefixSSEPair) error { targetAlias, targetURL, _ := mustExpandAlias(url) clnt, pErr := newClientFromAlias(targetAlias, targetURL) if pErr != nil { @@ -318,7 +331,13 @@ func mainRm(ctx *cli.Context) error { isStdin := ctx.Bool("stdin") olderThan := ctx.Int("older-than") newerThan := ctx.Int("newer-than") + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } + encKeyDB, perr := parseEncryptionKeys(sseKeys) + fatalIf(perr, "Unable to parse encryption keys") // Set color. console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) @@ -327,9 +346,9 @@ func mainRm(ctx *cli.Context) error { // Support multiple targets. for _, url := range ctx.Args() { if isRecursive { - err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan) + err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB) } else { - err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan) + err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB) } if rerr == nil { @@ -345,9 +364,9 @@ func mainRm(ctx *cli.Context) error { for scanner.Scan() { url := scanner.Text() if isRecursive { - err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan) + err = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB) } else { - err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan) + err = removeSingle(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB) } if rerr == nil { diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index 242d7bbf..22948f98 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -127,7 +127,7 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration // Channel which will receive objects whose URLs need to be shared objectsCh := make(chan *clientContent) - content, err := clnt.Stat(isIncomplete, isFetchMeta) + content, err := clnt.Stat(isIncomplete, isFetchMeta, "") if err != nil { return err.Trace(clnt.GetURL().String()) } diff --git a/cmd/stat-main.go b/cmd/stat-main.go index 52cf0e3f..3890a447 100644 --- a/cmd/stat-main.go +++ b/cmd/stat-main.go @@ -17,6 +17,7 @@ package cmd import ( + "os" "strings" "github.com/fatih/color" @@ -31,6 +32,10 @@ var ( Name: "recursive, r", Usage: "Stat recursively.", }, + cli.StringFlag{ + Name: "encrypt-key", + Usage: "Encrypt/Decrypt (using server-side encryption)", + }, } ) @@ -50,6 +55,10 @@ USAGE: FLAGS: {{range .VisibleFlags}}{{.}} {{end}} + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + EXAMPLES: 1. Stat all contents of mybucket on Amazon S3 cloud storage. $ {{.HelpName}} s3/mybucket/ @@ -59,6 +68,9 @@ EXAMPLES: 3. Stat files recursively on a local filesystem on Microsoft Windows. $ {{.HelpName}} --recursive C:\Users\Worf\ + + 4. Stat files which are encrypted on the server side + $ {{.HelpName}} --encrypt-key "s3/ferenginar=32byteslongsecretkeymustbegiven1" s3/ferenginar/klingon_opera_aktuh_maylotah.ogg `, } @@ -77,7 +89,6 @@ func checkStatSyntax(ctx *cli.Context) { // extract URLs. URLs := ctx.Args() isIncomplete := false - for _, url := range URLs { _, _, err := url2Stat(url) if err != nil && !isURLPrefixExists(url, isIncomplete) { @@ -109,6 +120,14 @@ func mainStat(ctx *cli.Context) error { args = []string{"."} } + sseKeys := os.Getenv("MC_ENCRYPT_KEY") + if key := ctx.String("encrypt-key"); key != "" { + sseKeys = key + } + + encKeyDB, err := parseEncryptionKeys(sseKeys) + fatalIf(err, "Unable to parse encryption keys") + var cErr error for _, targetURL := range args { var clnt Client @@ -116,7 +135,7 @@ func mainStat(ctx *cli.Context) error { fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") targetAlias, _, _ := mustExpandAlias(targetURL) - return doStat(clnt, isRecursive, targetAlias, targetURL) + return doStat(clnt, isRecursive, targetAlias, targetURL, encKeyDB) } return cErr diff --git a/cmd/stat.go b/cmd/stat.go index 2df8a371..53f7432e 100644 --- a/cmd/stat.go +++ b/cmd/stat.go @@ -110,7 +110,7 @@ func parseStat(targetAlias string, c *clientContent) statMessage { } // doStat - list all entities inside a folder. -func doStat(clnt Client, isRecursive bool, targetAlias, targetURL string) error { +func doStat(clnt Client, isRecursive bool, targetAlias, targetURL string, encKeyDB map[string][]prefixSSEPair) error { prefixPath := clnt.GetURL().Path separator := string(clnt.GetURL().Separator) @@ -144,7 +144,7 @@ func doStat(clnt Client, isRecursive bool, targetAlias, targetURL string) error continue } url := targetAlias + getKey(content) - _, stat, err := url2StatWithMetadata(url, true) + _, stat, err := url2StatWithMetadata(url, true, encKeyDB) if err != nil { stat = content } diff --git a/cmd/urls.go b/cmd/urls.go index 566f397f..990d8c56 100644 --- a/cmd/urls.go +++ b/cmd/urls.go @@ -26,6 +26,9 @@ type URLs struct { TargetContent *clientContent TotalCount int64 TotalSize int64 + encKeyDB map[string][]prefixSSEPair + SrcSSEKey string + TgtSSEKey string Error *probe.Error `json:"-"` } diff --git a/cmd/utils.go b/cmd/utils.go index 8143e146..47aff71e 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -17,11 +17,16 @@ package cmd import ( + "crypto/md5" "crypto/tls" + "encoding/base64" + "errors" "io" "math/rand" "os" + "regexp" "runtime" + "sort" "strings" "time" @@ -157,3 +162,70 @@ func getLookupType(l string) minio.BucketLookupType { } return minio.BucketLookupAuto } + +// sumMD5Base64 calculate md5sum for an input byte array, returns base64 encoded. +func sumMD5Base64(data []byte) string { + hash := md5.New() + hash.Write(data) + return base64.StdEncoding.EncodeToString(hash.Sum(nil)) +} + +// struct representing object prefix and sse keys association. +type prefixSSEPair struct { + prefix string + sseKey string +} + +// parse list of comma separated alias/prefix=sse key values entered on command line and +// construct a map of alias to prefix and sse pairs. +func parseEncryptionKeys(ssekeys string) (encMap map[string][]prefixSSEPair, err *probe.Error) { + encMap = make(map[string][]prefixSSEPair) + if ssekeys == "" { + return + } + fields := strings.Split(ssekeys, ",") + r := regexp.MustCompile("([^=\\s]+)=([^\\s]+)") + for _, field := range fields { + field = strings.TrimSpace(field) + matches := r.FindStringSubmatch(field) + if len(matches) != 3 { + return nil, probe.NewError(errors.New("sse-c prefix should be of the form prefix=key")) + } + key := matches[1] + value := matches[2] + alias, _ := url2Alias(key) + if len(value) != 32 { + return nil, probe.NewError(errors.New("sse-c key should be 32 bytes long")) + } + prefix := strings.TrimSpace(key) + if _, ok := encMap[alias]; !ok { + encMap[alias] = make([]prefixSSEPair, 0) + } + ps := prefixSSEPair{prefix: prefix, sseKey: value} + encMap[alias] = append(encMap[alias], ps) + } + // sort encryption keys in descending order of prefix length + for _, encKeys := range encMap { + sort.Sort(byPrefixLength(encKeys)) + } + return +} + +// byPrefixLength implements sort.Interface. +type byPrefixLength []prefixSSEPair + +func (p byPrefixLength) Len() int { return len(p) } +func (p byPrefixLength) Less(i, j int) bool { + return len(p[i].prefix) > len(p[j].prefix) +} +func (p byPrefixLength) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// get SSE Key if object prefix matches with given resource. +func getSSEKey(resource string, encKeys []prefixSSEPair) string { + for _, k := range encKeys { + if strings.HasPrefix(resource, k.prefix) { + return k.sseKey + } + } + return "" +} diff --git a/docs/minio-client-complete-guide.md b/docs/minio-client-complete-guide.md index 63f33063..bbaff837 100644 --- a/docs/minio-client-complete-guide.md +++ b/docs/minio-client-complete-guide.md @@ -317,6 +317,10 @@ USAGE: FLAGS: --help, -h Show help. + --encrypt-key value Decrypt object (using server-side encryption) + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values ``` *Example: Display the contents of a text file `myobject.txt`* @@ -325,6 +329,13 @@ FLAGS: mc cat play/mybucket/myobject.txt Hello Minio!! ``` + +*Example: Display the contents of a server encrypted object `myencryptedobject.txt`* + +```sh +mc cat --encrypt-key "play/mybucket=32byteslongsecretkeymustbegiven1" play/mybucket/myencryptedobject.txt +Hello Minio!! +``` ### Command `pipe` - Pipe to Object `pipe` command copies contents of stdin to a target. When no target is specified, it writes to stdout. @@ -334,7 +345,11 @@ USAGE: mc pipe [FLAGS] [TARGET] FLAGS: - --help, -h Help of pipe. + --help, -h Help of pipe. + --encrypt-key value Encrypt object (using server-side encryption) + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values ``` *Example: Stream MySQL database dump to Amazon S3 directly.* @@ -355,6 +370,10 @@ FLAGS: --recursive, -r Copy recursively. --storage-class value, -sc value Set storage class for object. --help, -h Show help. + --encrypt-key value Encrypt/Decrypt objects (using server-side encryption) + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values ``` *Example: Copy a text file to an object storage.* @@ -371,6 +390,20 @@ mc cp --storage-class REDUCED_REDUNDANCY myobject.txt play/mybucket myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0 ``` +*Example: Copy a server-side encrypted file to an object storage.* + +```sh +mc cp --recursive --encrypt-key "s3/documents/=32byteslongsecretkeymustbegiven1 , myminio/documents/=32byteslongsecretkeymustbegiven2" s3/documents/myobject.txt myminio/documents/ +myobject.txt: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0 +``` + +*Example: Perform key-rotation on a server-side encrypted object* + +```sh +mc cp --encrypt-key 'myminio1/mybucket=32byteslongsecretkeymustgenerate , myminio2/mybucket/=32byteslongsecretkeymustgenerat1' myminio1/mybucket/encryptedobject myminio2/mybucket/encryptedobject +encryptedobject: 14 B / 14 B ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.00 % 41 B/s 0 +``` +Notice that two different aliases myminio1 and myminio2 are used for the same endpoint to provide the old secretkey and the newly rotated key. ### Command `rm` - Remove Buckets and Objects Use `rm` command to remove file or bucket @@ -388,6 +421,11 @@ FLAGS: --fake Perform a fake remove operation. --stdin Read object list from STDIN. --older-than value Remove objects older than N days. (default: 0) + --encrypt-key value Encrypt/Decrypt objects (using server-side encryption) +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values + + ``` *Example: Remove a single object.* @@ -396,6 +434,12 @@ FLAGS: mc rm play/mybucket/myobject.txt Removed ‘play/mybucket/myobject.txt’. ``` +*Example: Remove an encrypted object.* + +```sh +mc rm --encrypt-key "play/mybucket=32byteslongsecretkeymustbegiven1" play/mybucket/myobject.txt +Removed ‘play/mybucket/myobject.txt’. +``` *Example: Recursively remove a bucket and all its contents. Since this is a dangerous operation, you must explicitly pass `--force` option.* @@ -510,7 +554,11 @@ FLAGS: --watch, -w Watch and mirror for changes. --remove Remove extraneous file(s) on target. --storage-class value, --sc value Set storage class for object. -``` + --encrypt-key value Encrypt/Decrypt objects (using server-side encryption) + +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values +``` *Example: Mirror a local directory to 'mybucket' on https://play.minio.io:9000.* @@ -813,7 +861,10 @@ USAGE: FLAGS: --help, -h Show help. --recursive, -r Stat recursively. + --encrypt-key value Encrypt/Decrypt (using server-side encryption) +ENVIRONMENT VARIABLES: + MC_ENCRYPT_KEY: List of comma delimited prefix=secret values ``` *Example: Display information on a bucket named "mybucket" on https://play.minio.io:9000.* @@ -827,6 +878,22 @@ Size : 0B Type : folder ``` +*Example: Display information on an encrypted object "myobject" in "mybucket" on https://play.minio.io:9000.* + + +```sh +mc stat play/mybucket/myobject --encrypt-key "play/mybucket=32byteslongsecretkeymustbegiven1" +Name : myobject +Date : 2018-03-02 11:47:13 PST +Size : 132B +ETag : d03ba22cd78282b7aef705bf31b8cded +Type : file +Metadata : + Content-Type : application/octet-stream + X-Amz-Server-Side-Encryption-Customer-Key-Md5 : 4xSRdYsabg+s2nlsHKhgnw== + X-Amz-Server-Side-Encryption-Customer-Algorithm: AES256 +``` + *Example: Display information on objects contained in the bucket named "mybucket" on https://play.minio.io:9000.* diff --git a/functional-tests.sh b/functional-tests.sh index 558aca99..9cfe99a1 100755 --- a/functional-tests.sh +++ b/functional-tests.sh @@ -77,6 +77,8 @@ if [ "$ENABLE_HTTPS" != "1" ]; then fi SERVER_ALIAS="myminio" +SERVER_ALIAS_TLS="myminio-ssl" + BUCKET_NAME="mc-test-bucket-$RANDOM" WATCH_OUT_FILE="$WORK_DIR/watch.out-$RANDOM" @@ -574,6 +576,203 @@ function test_config_host_add_error() log_success "$start_time" "${FUNCNAME[0]}" } +function test_put_object_with_sse() +{ + show "${FUNCNAME[0]}" + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + # put encrypted object; then delete with correct secret key + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_put_object_with_sse_error() +{ + show "${FUNCNAME[0]}" + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven" + # put object with invalid encryption key; should fail + assert_failure "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_cat_object_with_sse() +{ + show "${FUNCNAME[0]}" + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + # put encrypted object; then cat object correct secret key + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cat --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_cat_object_with_sse_error() +{ + show "${FUNCNAME[0]}" + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + # put encrypted object; then cat object with no secret key + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_failure "$start_time" "${FUNCNAME[0]}" mc_cmd cat "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_copy_object_with_sse() +{ + # test server side copy and remove operation - target is unencrypted while source is encrypted + show "${FUNCNAME[0]}" + start_time=$(get_time) + prefix="prefix" + object_name="mc-test-object-$RANDOM" + + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}=32byteslongsecretkeymustbegiven1" + # create encrypted object on server + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # now do a server side copy and store it unencrypted. + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + # cat the unencrypted destination object. should return data without any error + assert_success "$start_time" "${FUNCNAME[0]}" "${MC_CMD[@]}" cat "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" > "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" show_on_failure $? "unable to download object using 'mc cat'" + assert_success "$start_time" "${FUNCNAME[0]}" check_md5sum "$FILE_1_MB_MD5SUM" "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${object_name}.downloaded" + # mc rm on encrypted object without encryption key should fail + assert_failure "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # mc rm on encrypted object with encryption key should pass + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # mc rm on unencrypted destination object should pass + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_copy_object_with_sse2() +{ + # test server side copy and remove operation - target is encrypted with different key + show "${FUNCNAME[0]}" + start_time=$(get_time) + prefix="prefix" + object_name="mc-test-object-$RANDOM" + + cli_flag1="${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}=32byteslongsecretkeymustbegiven1" + cli_flag2="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven2" + + # create encrypted object on server + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag1}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # now do a server side copy and store it eith different encryption key. + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag1},${cli_flag2}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + # cat the destination object with the new key. should return data without any error + assert_success "$start_time" "${FUNCNAME[0]}" "${MC_CMD[@]}" cat --encrypt-key "${cli_flag2}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" > "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" show_on_failure $? "unable to download object using 'mc cat'" + assert_success "$start_time" "${FUNCNAME[0]}" check_md5sum "$FILE_1_MB_MD5SUM" "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${object_name}.downloaded" + # mc rm on src object with first encryption key should pass + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag1}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # mc rm on encrypted destination object with second encryption key should pass + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag2}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_sse_key_rotation() +{ + # test server side copy and remove operation - target is encrypted with different key + show "${FUNCNAME[0]}" + start_time=$(get_time) + prefix="prefix" + object_name="mc-test-object-$RANDOM" + old_key="32byteslongsecretkeymustbegiven1" + new_key="32byteslongsecretkeymustbegiven2" + cli_flag1="${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}=${old_key}" + cli_flag2="${SERVER_ALIAS_TLS}/${BUCKET_NAME}=${new_key}" + + # create encrypted object on server + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag1}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" + # now do a server side copy on same object and do a key rotation + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag1}, ${cli_flag2}" "${SERVER_ALIAS}/${BUCKET_NAME}/${prefix}/${object_name}" "${SERVER_ALIAS_TLS}/${BUCKET_NAME}/${object_name}" + # cat the object with the new key. should return data without any error + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cat --encrypt-key "${cli_flag2}" "${SERVER_ALIAS_TLS}/${BUCKET_NAME}/${object_name}" > "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" show_on_failure $? "unable to download object using 'mc cat'" + assert_success "$start_time" "${FUNCNAME[0]}" check_md5sum "$FILE_1_MB_MD5SUM" "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${object_name}.downloaded" + # mc rm on object with old key should fail + assert_failure "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag1}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + # mc rm on encrypted object with second encryption key should pass + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag2}" "${SERVER_ALIAS_TLS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_mirror_with_sse() +{ + # test if mirror operation works with encrypted objects + show "${FUNCNAME[0]}" + + start_time=$(get_time) + bucket_name="mc-test-bucket-$RANDOM" + cli_flag="${SERVER_ALIAS}/${bucket_name}=32byteslongsecretkeymustbegiven1" + + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd mb "${SERVER_ALIAS}/${bucket_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd mirror --encrypt-key "${cli_flag}" "$DATA_DIR" "${SERVER_ALIAS}/${bucket_name}" + diff -bB <(ls "$DATA_DIR") <("${MC_CMD[@]}" --json ls "${SERVER_ALIAS}/${bucket_name}" | jq -r .key) >/dev/null 2>&1 + assert_success "$start_time" "${FUNCNAME[0]}" show_on_failure $? "mirror and list differs" + # remove recursively with correct encryption key + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --force --recursive --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${bucket_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_rm_object_with_sse() +{ + show "${FUNCNAME[0]}" + + # test whether remove fails for encrypted object if secret key not provided. + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_failure "$start_time" "${FUNCNAME[0]}" mc_cmd rm "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_get_object_with_sse() +{ + show "${FUNCNAME[0]}" + + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_1_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" check_md5sum "$FILE_1_MB_MD5SUM" "${object_name}.downloaded" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag}" "${object_name}.downloaded" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + +function test_put_object_multipart_sse() +{ + show "${FUNCNAME[0]}" + + start_time=$(get_time) + object_name="mc-test-object-$RANDOM" + cli_flag="${SERVER_ALIAS}/${BUCKET_NAME}=32byteslongsecretkeymustbegiven1" + + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd cp --encrypt-key "${cli_flag}" "${FILE_65_MB}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd rm --encrypt-key "${cli_flag}" "${SERVER_ALIAS}/${BUCKET_NAME}/${object_name}" + + log_success "$start_time" "${FUNCNAME[0]}" +} + function run_test() { test_make_bucket @@ -600,6 +799,20 @@ function run_test() test_watch_object fi + if [ "$ENABLE_HTTPS" == "1" ]; then + test_put_object_with_sse + test_put_object_with_sse_error + test_put_object_multipart_sse + test_get_object_with_sse + test_cat_object_with_sse + test_cat_object_with_sse_error + test_copy_object_with_sse + test_copy_object_with_sse2 + test_sse_key_rotation + test_mirror_with_sse + test_rm_object_with_sse + fi + test_config_host_add test_config_host_add_error @@ -653,8 +866,9 @@ function __init__() echo "unable to get md5sum of $FILE_65_MB" exit 1 fi - assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd config host add "${SERVER_ALIAS}" "$ENDPOINT" "$ACCESS_KEY" "$SECRET_KEY" + assert_success "$start_time" "${FUNCNAME[0]}" mc_cmd config host add "${SERVER_ALIAS_TLS}" "$ENDPOINT" "$ACCESS_KEY" "$SECRET_KEY" + set +e }