Welcome to mirror list, hosted at ThFree Co, Russian Federation.

S3IAM.cs « S3 « Backend « Library « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 606f52d89ae73230fd03e4e5e86e6f6be85521a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
//  Copyright (C) 2015, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library 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
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Linq;
using Duplicati.Library.Interface;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace Duplicati.Library.Backend
{
    public class S3IAM : IWebModule
    {
        private const string KEY_OPERATION = "s3-operation";
        private const string KEY_USERNAME = "s3-username";
        private const string KEY_PASSWORD = "s3-password";
        private const string KEY_PATH = "s3-path";

        public enum Operation
        {
            CanCreateUser,
            CreateIAMUser,
            GetPolicyDoc
        }

        public const string POLICY_DOCUMENT_TEMPLATE = 
@"
{
    ""Version"": ""2012-10-17"",
    ""Statement"": [
        {
            ""Sid"": ""Stmt1390497858034"",
            ""Effect"": ""Allow"",
            ""Action"": [
                ""s3:GetObject"",
                ""s3:PutObject"",
                ""s3:ListBucket"",
                ""s3:DeleteObject""
            ],
            ""Resource"": [
                ""arn:aws:s3:::bucket-name"",
                ""arn:aws:s3:::bucket-name/*""
            ]
        }
    ]
}
";

        public S3IAM()
        {
        }

        public string Key { get { return "s3-iamconfig"; } }

        public string DisplayName { get { return "S3 IAM support module"; } }

        public string Description { get { return "Exposes S3 IAM manipulation as a web module"; } }


        public IList<ICommandLineArgument> SupportedCommands
        {
            get
            {
                return new List<ICommandLineArgument>(new ICommandLineArgument[] {
                    new CommandLineArgument(KEY_OPERATION, CommandLineArgument.ArgumentType.Enumeration, "The operation to perform", "Selects the operation to perform", null, Enum.GetNames(typeof(Operation))),
                    new CommandLineArgument(KEY_USERNAME, CommandLineArgument.ArgumentType.String, "The username", "The Amazon Access Key ID"),
                    new CommandLineArgument(KEY_PASSWORD, CommandLineArgument.ArgumentType.String, "The password", "The Amazon Secret Key"),
                });
            }
        }

        public IDictionary<string, string> Execute(IDictionary<string, string> options)
        {
            string operationstring;
            string username;
            string password;
            string path;
            Operation operation;

            options.TryGetValue(KEY_OPERATION, out operationstring);
            options.TryGetValue(KEY_USERNAME, out username);
            options.TryGetValue(KEY_PASSWORD, out password);
            options.TryGetValue(KEY_PATH, out path);

            if (string.IsNullOrWhiteSpace(operationstring))
                throw new ArgumentNullException(KEY_OPERATION);

            if (!Enum.TryParse(operationstring, true, out operation))
                throw new ArgumentException(string.Format("Unable to parse {0} as an operation", operationstring));

            switch (operation)
            {
                case Operation.GetPolicyDoc:
                    if (string.IsNullOrWhiteSpace(path))
                        throw new ArgumentNullException(KEY_PATH);
                    return GetPolicyDoc(path);

                case Operation.CreateIAMUser:
                    if (string.IsNullOrWhiteSpace(username))
                        throw new ArgumentNullException(KEY_USERNAME);
                    if (string.IsNullOrWhiteSpace(password))
                        throw new ArgumentNullException(KEY_PASSWORD);
                    if (string.IsNullOrWhiteSpace(path))
                        throw new ArgumentNullException(KEY_PATH);
                    return CreateUnprivilegedUser(username, password, path);

                case Operation.CanCreateUser:
                default:
                    if (string.IsNullOrWhiteSpace(username))
                        throw new ArgumentNullException(KEY_USERNAME);
                    if (string.IsNullOrWhiteSpace(password))
                        throw new ArgumentNullException(KEY_PASSWORD);
                    return CanCreateUser(username, password);
            }
        }

        private Dictionary<string, string> GetPolicyDoc(string path)
        {
            var dict = new Dictionary<string, string>();
            dict["doc"] = GeneratePolicyDoc(path);
            return dict;
        }

        private string GeneratePolicyDoc(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException("path");

            path = path.Trim().Trim('/').Trim();

            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentException("Invalid value for path");

            var bucketname = path.Split('/').First();

            return POLICY_DOCUMENT_TEMPLATE.Replace("bucket-name", bucketname).Trim();
        }

        private Dictionary<string, string> CanCreateUser(string awsid, string awskey)
        {
            var dict = new Dictionary<string, string>();
            var cl = new AmazonIdentityManagementServiceClient(awsid, awskey);
            try
            {
                var user = cl.GetUser().User;

                dict["isroot"] = "False"; //user.Arn.EndsWith(":root", StringComparison.Ordinal).ToString();
                dict["arn"] = user.Arn;
                dict["id"] = user.UserId;
                dict["name"] = user.UserName;

                dict["isroot"] = (cl.SimulatePrincipalPolicy(new SimulatePrincipalPolicyRequest() { PolicySourceArn = user.Arn, ActionNames = new[] { "iam:CreateUser" }.ToList() }).EvaluationResults.First().EvalDecision == PolicyEvaluationDecisionType.Allowed).ToString();
            }
            catch (Exception ex)
            {
                dict["ex"] = ex.ToString();
                dict["error"] = ex.Message;
            }

            return dict;
        }

        private Dictionary<string, string> CreateUnprivilegedUser(string awsid, string awskey, string path)
        {
            var now = Library.Utility.Utility.SerializeDateTime(DateTime.Now);
            var username = string.Format("duplicati-autocreated-backup-user-{0}", now);
            var policyname = string.Format("duplicati-autocreated-policy-{0}", now);
            var policydoc = GeneratePolicyDoc(path);

            var cl = new AmazonIdentityManagementServiceClient(awsid, awskey);
            var user = cl.CreateUser(new CreateUserRequest(username)).User;
            cl.PutUserPolicy(new PutUserPolicyRequest(
                user.UserName,
                policyname,
                policydoc
            ));
            var key = cl.CreateAccessKey(new CreateAccessKeyRequest() { UserName = user.UserName }).AccessKey;

            var dict = new Dictionary<string, string>();
            dict["accessid"] = key.AccessKeyId;
            dict["secretkey"] = key.SecretAccessKey;
            dict["username"] = key.UserName;

            return dict;
        }
    }
}