├── AWSSAMLCredentials
├── AWSSAMLCredentials.suo
├── AWSSAMLCredentials.v12.suo
├── AWSSAMLCredentials.sln
└── ClassLibrary1
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── AWSSAMLCredentials.csproj
│ ├── AWSSAMLUtils.cs
│ └── AWSSAML.cs
├── NOTICE.TXT
├── README.md
└── LICENSE.txt
/AWSSAMLCredentials/AWSSAMLCredentials.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/aws-saml-adfs-cmdlet-sample/HEAD/AWSSAMLCredentials/AWSSAMLCredentials.suo
--------------------------------------------------------------------------------
/AWSSAMLCredentials/AWSSAMLCredentials.v12.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/aws-saml-adfs-cmdlet-sample/HEAD/AWSSAMLCredentials/AWSSAMLCredentials.v12.suo
--------------------------------------------------------------------------------
/NOTICE.TXT:
--------------------------------------------------------------------------------
1 | Copyright 2015-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
4 |
5 | http://aws.amazon.com/apache2.0/
6 |
7 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
--------------------------------------------------------------------------------
/AWSSAMLCredentials/AWSSAMLCredentials.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.31101.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWSSAMLCredentials", "ClassLibrary1\AWSSAMLCredentials.csproj", "{A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/AWSSAMLCredentials/ClassLibrary1/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("AWSSAML")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("AWSSAML")]
13 | [assembly: AssemblyCopyright("Copyright © 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("64e2e6d1-873a-40b3-ab16-431868194ebc")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/AWSSAMLCredentials/ClassLibrary1/AWSSAMLCredentials.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {A7DA1D48-C767-4D67-B7F6-C7D841B0DB1A}
8 | Library
9 | Properties
10 | AWSSAML
11 | AWSSAML
12 | v4.5
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 | C:\Program Files (x86)\AWS SDK for .NET\bin\Net45\AWSSDK.Core.dll
35 |
36 |
37 | C:\Program Files (x86)\AWS SDK for .NET\bin\Net45\AWSSDK.SecurityToken.dll
38 |
39 |
40 |
41 |
42 | False
43 | C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
65 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # aws-saml-adfs-cmdlet-sample
2 | A reference Windows PowerShell module that obtains and sets temporary AWS security credentials in a Windows PowerShell session using SAML and AD FS. The code can be adapted for use in any C# .NET application.
3 |
4 | ## Prerequisites
5 |
6 | To use the cmdlet, you must have:
7 |
8 | - Active Directory Federation Services (AD FS) correctly integrated with your AWS account for console access using only your organizational credentials. See [Enabling Federation to AWS Using Windows Active Directory, AD FS, and SAML 2.0](http://blogs.aws.amazon.com/security/post/Tx71TWXXJ3UI14/Enabling-Federation-to-AWS-using-Windows-Active-Directory-ADFS-and-SAML-2-0), if you need instructions about this integration. Note that these steps are similar if you're using AD FS 3.0.
9 | - To run, the latest version of the [AWS Tools for Windows PowerShell](https://aws.amazon.com/powershell/) installed on your local workstation.
10 | - To compile, the latest version of the [AWS SDK for .NET](https://aws.amazon.com/sdk-for-net/) installed on your local workstation.
11 |
12 | ## How to compile the PowerShell module
13 | ```
14 | PS > C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe .\AWSSAMLCredentials\AWSSAMLCredentials.sln /p:Configuration=Release
15 | ```
16 |
17 | ## How to use the Set-AWSSAMLCredentials cmdlet
18 |
19 | ```
20 | PS > Import-Module .\AWSSAMLCredentials\ClassLibrary1\bin\Release\AWSSAML.dll
21 | ```
22 |
23 | Now, let's look at how we authenticate with the AD FS identity provider to obtain temporary AWS credentials. Using the `AWSSAMLCredentials` cmdlet, we can interactively provide Windows Active Directory credentials and then select an AWS role to which the user has access.
24 |
25 | When running the `Set-AWSSAMLCredentials` cmdlet be sure to replace the **example AD FS hostname** with your own actual AD FS hostname.
26 |
27 | ```
28 | PS > Set-AWSSAMLCredentials -IdentityProviderUrl "https://**adfs.example.com**/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices" -UseCurrentCredentials $false
29 | ```
30 |
31 | ```
32 | username: adminaduser
33 | password: ************
34 | domain: example.com
35 |
36 | Please choose the role you would like to assume:
37 | [0]: arn:aws:iam::012345678912:role/ADFS-Production
38 | [1]: arn:aws:iam::012345678912:role/ADFS-Dev
39 |
40 | Selection: 0
41 | ```
42 |
43 | Rather than typing your Windows credentials every time, the `Set-AWSSAMLCredentials` cmdlet can obtain temporary AWS credentials using your existing Active Directory credentials.
44 |
45 | ```
46 | PS > Set-AWSSAMLCredentials -IdentityProviderUrl "https://**adfs.example.com**/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices" -UseCurrentCredentials $true
47 | ```
48 |
49 | ```
50 | Please choose the role you would like to assume:
51 | [0]: arn:aws:iam::012345678912:role/ADFS-Production
52 | [1]: arn:aws:iam::012345678912:role/ADFS-Dev
53 |
54 | Selection: 0
55 | ```
56 |
57 | To obtain temporary AWS credentials non-interactively, the `RoleIndex` parameter can be used to select an AWS role. In the following command, we obtain temporary credentials by using one of the roles you have pre-configured in AD FS (such as the `ADFS-Production` role [item 0 in the list above]).
58 |
59 | ```
60 | PS > Set-AWSSAMLCredentials -IdentityProviderUrl "https://**adfs.example.com**/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices" -RoleIndex 0
61 | ```
62 |
63 | Now let's use the temporary AWS credentials obtained by using the `Set-AWSSAMLCredentials` cmdlet to interact with AWS service APIs.
64 |
65 | **Example 1:** In this example, we will list all the available Amazon S3 buckets in the AWS account of the role we have assumed. This is a common task for administrators managing S3 from the Windows PowerShell command line.
66 | ```
67 | PS > Get-S3Bucket
68 |
69 | CreationDate BucketName
70 | ------------ ----------
71 | 7/25/2013 3:16:56 AM mybucket1
72 | 4/15/2015 12:46:50 AM mybucket2
73 | 4/15/2015 6:15:53 AM mybucket3
74 | 1/12/2015 11:20:16 PM mybucket4
75 | ```
76 |
77 | Notice how we didn't need to provide credentials when we called `Get-S3Bucket` cmdlet. Running the `Set-AWSSAMLCredentials` cmdlet has made temporary credentials available to the AWS Tools for Windows in the current PowerShell session. These credentials will expire after 1 hour. When the credentials expire, the Windows PowerShell module can be rerun to refresh the credentials without any user interaction. Note that I have again selected the role using the `RoleIndex` parameter.
78 |
79 | ```
80 | PS > Set-AWSSAMLCredentials –IdentityProviderUrl "https://**adfs.example.com**/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices" -UseCurrentCredentials $true –RoleIndex 0
81 | ```
82 |
83 | **Example 2:** Now let's list all Amazon EC2 instances in the Sydney region. You may want to do this to get a list of all the EC2 instances in the region in order to manage your EC2 fleet.
84 |
85 | ```
86 | PS > (Get-Ec2Instance –Region ap-southeast-2).Instances | Select InstanceType, @{Name="Servername";Expression={$\_.tags | where key -eq "Name" | Select Value -Expand Value}}
87 |
88 | InstanceType Servername
89 | ------------ ----------
90 | t2.small DC2
91 | t1.micro NAT1
92 | t1.micro RDGW1
93 | t1.micro RDGW2
94 | t1.micro NAT2
95 | t2.small DC1
96 | t2.micro BUILD
97 | ```
98 |
99 | ## License
100 |
101 | This sample application is distributed under the
102 | [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
103 |
104 |
--------------------------------------------------------------------------------
/AWSSAMLCredentials/ClassLibrary1/AWSSAMLUtils.cs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using System.Threading.Tasks;
20 |
21 | using System.IO;
22 |
23 | using System.Net;
24 | using System.Net.Http;
25 |
26 | using System.Xml;
27 | using System.Text.RegularExpressions;
28 |
29 | using Amazon.SecurityToken;
30 | using Amazon.Runtime;
31 | using Amazon.SecurityToken.Model;
32 |
33 | namespace AWSSAML
34 | {
35 | class AWSSAMLUtils
36 | {
37 | public string GetSamlAssertion(string identityProvider)
38 | {
39 |
40 | string samlAssertion = "";
41 | HttpWebResponse response = getResult(identityProvider);
42 | string responseStreamData;
43 |
44 |
45 | using (StreamReader reader = new StreamReader(response.GetResponseStream()))
46 | {
47 | responseStreamData = reader.ReadToEnd();
48 | }
49 |
50 | Regex reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
51 | MatchCollection matches = reg.Matches(responseStreamData);
52 | string last = null;
53 | foreach (Match m in matches)
54 | {
55 | last = m.Groups[1].Value;
56 | samlAssertion = last;
57 | }
58 |
59 | return samlAssertion;
60 | }
61 |
62 | public string[] GetAwsSamlRoles(string samlAssertion)
63 | {
64 | string[] awsSamlRoles = null;
65 | XmlDocument doc = new XmlDocument();
66 | StringBuilder sb = new StringBuilder();
67 | StringWriter sw = new StringWriter(sb);
68 | byte[] decoded = Convert.FromBase64String(samlAssertion);
69 | string deflated = Encoding.UTF8.GetString(decoded);
70 |
71 | doc.LoadXml(deflated);
72 | using (XmlTextWriter tw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
73 | {
74 | doc.WriteTo(tw);
75 | }
76 |
77 | XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
78 | nsmgr.AddNamespace("response", "urn:oasis:names:tc:SAML:2.0:assertion");
79 | string xPathString = "//response:Attribute[@Name='https://aws.amazon.com/SAML/Attributes/Role']";
80 | XmlNodeList roleAttributeNodes = doc.DocumentElement.SelectNodes(xPathString, nsmgr);
81 |
82 | if (roleAttributeNodes != null && roleAttributeNodes.Count > 0)
83 | {
84 | XmlNodeList roleNodes = roleAttributeNodes[0].ChildNodes;
85 |
86 | awsSamlRoles = new string[roleNodes.Count];
87 |
88 | for (int i = 0; i < roleNodes.Count; i++)
89 | {
90 | XmlNode roleNode = roleNodes[i];
91 | if (roleNode.InnerText.Length > 0)
92 | {
93 | string[] chunks = roleNode.InnerText.Split(',');
94 | string newAwsSamlRole = chunks[0] + ',' + chunks[1];
95 | awsSamlRoles[i] = newAwsSamlRole;
96 | }
97 | }
98 | }
99 |
100 | return awsSamlRoles;
101 | }
102 |
103 | public SessionAWSCredentials GetSamlRoleCredentails(string samlAssertion, string awsRole)
104 | {
105 | string[] role = awsRole.Split(',');
106 |
107 | AssumeRoleWithSAMLRequest samlRequest = new AssumeRoleWithSAMLRequest();
108 | samlRequest.SAMLAssertion = samlAssertion;
109 | samlRequest.RoleArn = role[1];
110 | samlRequest.PrincipalArn = role[0];
111 | samlRequest.DurationSeconds = 3600;
112 |
113 | AmazonSecurityTokenServiceClient sts;
114 | AssumeRoleWithSAMLResponse samlResponse;
115 | try {
116 | sts = new AmazonSecurityTokenServiceClient();
117 | samlResponse = sts.AssumeRoleWithSAML(samlRequest);
118 | }
119 | catch
120 | {
121 | sts = new AmazonSecurityTokenServiceClient("a", "b", "c");
122 | samlResponse = sts.AssumeRoleWithSAML(samlRequest);
123 | }
124 |
125 | SessionAWSCredentials sessionCredentials = new SessionAWSCredentials(
126 | samlResponse.Credentials.AccessKeyId,
127 | samlResponse.Credentials.SecretAccessKey,
128 | samlResponse.Credentials.SessionToken);
129 |
130 | return sessionCredentials;
131 | }
132 |
133 | private HttpWebResponse getResult(string url)
134 | {
135 | Uri uri = new Uri(url);
136 |
137 | CredentialCache credCache = new CredentialCache();
138 | credCache.Add(uri, "NTLM", CredentialCache.DefaultNetworkCredentials);
139 |
140 | HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
141 | request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
142 | request.KeepAlive = true;
143 | request.Credentials = credCache;
144 | request.PreAuthenticate = true;
145 | request.AllowAutoRedirect = true;
146 | request.CookieContainer = new System.Net.CookieContainer();
147 |
148 | HttpWebResponse response = (HttpWebResponse)request.GetResponse();
149 |
150 | return response;
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | Note: Other license terms may apply to certain, identified software
177 | files contained within or distributed with the accompanying software
178 | if such terms are included in the directory containing the accompanying
179 | software. Such other license terms will then apply in lieu of the terms
180 | of the software license above.
181 |
182 | END OF TERMS AND CONDITIONS
183 |
--------------------------------------------------------------------------------
/AWSSAMLCredentials/ClassLibrary1/AWSSAML.cs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Linq;
18 | using System.Text;
19 | using System.Threading.Tasks;
20 |
21 | using System.Runtime.InteropServices;
22 | using System.Security.Principal;
23 |
24 | using System.Management.Automation;
25 | using System.Collections.ObjectModel;
26 | using System.Management.Automation.Runspaces;
27 |
28 | using System.Net;
29 |
30 | using Amazon;
31 | using Amazon.SecurityToken;
32 | using Amazon.Runtime;
33 |
34 | namespace AWSSAML
35 | {
36 | [Cmdlet(VerbsCommon.Set, "AWSSAMLCredentials")]
37 | public class SetAWSSAMLCredentials : PSCmdlet
38 | {
39 | [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
40 | private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
41 | int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
42 |
43 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
44 | private extern static bool CloseHandle(IntPtr handle);
45 |
46 | [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
47 | private extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
48 | int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
49 |
50 | private IntPtr tokenHandle = new IntPtr(0);
51 | private IntPtr dupeTokenHandle = new IntPtr(0);
52 | private WindowsImpersonationContext impersonatedUser;
53 |
54 | private string identityProviderUrl;
55 | [Parameter(
56 | Mandatory=true,
57 | ValueFromPipeline=true,
58 | ValueFromPipelineByPropertyName=true,
59 | Position=0,
60 | HelpMessage="The identity provider URL."
61 | )]
62 | public string IdentityProviderUrl
63 | {
64 | get { return identityProviderUrl; }
65 | set { identityProviderUrl = value; }
66 | }
67 |
68 | private bool useCurrentCredentials = true;
69 | [Parameter(
70 | Mandatory = false,
71 | ValueFromPipeline = true,
72 | ValueFromPipelineByPropertyName = true,
73 | Position = 1,
74 | HelpMessage = "Use current user Windows credentials."
75 | )]
76 | public bool UseCurrentCredentials
77 | {
78 | get { return useCurrentCredentials; }
79 | set { useCurrentCredentials = value; }
80 | }
81 |
82 | private int roleIndex = Int16.MaxValue;
83 | [Parameter(
84 | Mandatory = false,
85 | ValueFromPipeline = true,
86 | ValueFromPipelineByPropertyName = true,
87 | Position = 2,
88 | HelpMessage = "Role index to use."
89 | )]
90 | public int RoleIndex
91 | {
92 | get { return roleIndex; }
93 | set { roleIndex = value; }
94 | }
95 |
96 | protected override void ProcessRecord()
97 | {
98 | try
99 | {
100 | AWSSAMLUtils awsSamlUtils = new AWSSAMLUtils();
101 | SessionAWSCredentials awsSessionCredentials = null;
102 |
103 | ICredentials userCredentials = AskUserForCredentials(useCurrentCredentials);
104 |
105 | Uri uri = new Uri(identityProviderUrl);
106 | NetworkCredential networkCredentials = userCredentials.GetCredential(uri, "");
107 | if (CredentialCache.DefaultCredentials != userCredentials)
108 | {
109 | ImpersonateUser(networkCredentials.UserName, networkCredentials.Password, networkCredentials.Domain);
110 | }
111 |
112 | string samlAssertion = awsSamlUtils.GetSamlAssertion(identityProviderUrl);
113 | string[] awsSamlRoles = awsSamlUtils.GetAwsSamlRoles(samlAssertion);
114 | UnImpersonateUser();
115 |
116 | string awsSamlRole = null;
117 | if (roleIndex < awsSamlRoles.Length)
118 | {
119 | awsSamlRole = awsSamlRoles[roleIndex];
120 | }
121 | else
122 | {
123 | awsSamlRole = AskUserForAwsSamlRole(awsSamlRoles);
124 | }
125 |
126 | awsSessionCredentials = awsSamlUtils.GetSamlRoleCredentails(samlAssertion, awsSamlRole);
127 | SetPowershellSamlProfile(awsSessionCredentials.GetCredentials());
128 | }
129 | catch
130 | {
131 | throw;
132 | }
133 | }
134 |
135 | private ICredentials AskUserForCredentials(bool useCurrentCredentials)
136 | {
137 | if (useCurrentCredentials)
138 | {
139 | return CredentialCache.DefaultCredentials;
140 | }
141 | else
142 | {
143 | string userName, password, domain = null;
144 |
145 | Console.Write("username: ");
146 | userName = Console.ReadLine();
147 |
148 | Console.Write("password: ");
149 | password = GetPasswordViaConsole();
150 | Console.WriteLine();
151 |
152 | Console.Write("domain: ");
153 | domain = Console.ReadLine();
154 |
155 | return new NetworkCredential(userName, password, domain);
156 | }
157 | }
158 |
159 | private string AskUserForAwsSamlRole(string[] awsSamlRoles)
160 | {
161 | Console.WriteLine("Please choose the role you would like to assume:");
162 | for (int i = 0; i < awsSamlRoles.Length; i++)
163 | {
164 | string[] awsSamlRole = awsSamlRoles[i].Split(',');
165 | Console.WriteLine(String.Format(" [{0}]: {1} ", i, awsSamlRole[1]));
166 | }
167 |
168 | Console.Write("Selection: ");
169 |
170 | ConsoleKeyInfo key;
171 | int index = 0;
172 |
173 | do
174 | {
175 | key = Console.ReadKey();
176 | index = int.Parse(key.KeyChar.ToString());
177 | } while (!Char.IsNumber(key.KeyChar) || index > awsSamlRoles.Length - 1);
178 | Console.WriteLine();
179 |
180 | return awsSamlRoles[index];
181 | }
182 |
183 | private string GetPasswordViaConsole()
184 | {
185 | string password = "";
186 | ConsoleKeyInfo key;
187 |
188 | do
189 | {
190 | key = Console.ReadKey(true);
191 |
192 | if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
193 | {
194 | password += key.KeyChar;
195 | Console.Write("*");
196 | }
197 | else
198 | {
199 | if (key.Key == ConsoleKey.Backspace && password.Length > 0)
200 | {
201 | password = password.Substring(0, (password.Length - 1));
202 | Console.Write("\b \b");
203 | }
204 | }
205 | }
206 | while (key.Key != ConsoleKey.Enter);
207 |
208 | return password;
209 | }
210 |
211 | private void SetPowershellSamlProfile(ImmutableCredentials awsSessionCredentials)
212 | {
213 | // create a pipeline and feed it the script text
214 | string script = String.Format("Set-AWSCredentials -AccessKey '{0}' -SecretKey '{1}' -SessionToken '{2}'", awsSessionCredentials.AccessKey, awsSessionCredentials.SecretKey, awsSessionCredentials.Token);
215 |
216 | Runspace theRunSpace = System.Management.Automation.Runspaces.Runspace.DefaultRunspace;
217 |
218 | if (theRunSpace.RunspaceStateInfo.State == RunspaceState.Opened)
219 | {
220 | using (Pipeline thePipeline = theRunSpace.CreateNestedPipeline(script, true))
221 | {
222 | Collection theRetVal = thePipeline.Invoke();
223 | }
224 | }
225 | }
226 |
227 | private void ImpersonateUser(string userName, string password, string domainName)
228 | {
229 | const int LOGON32_TYPE_NEW_CREDENTIALS = 9;
230 | const int LOGON32_PROVIDER_WINNT50 = 3;
231 | const int SecurityImpersonation = 2;
232 |
233 | tokenHandle = IntPtr.Zero;
234 | dupeTokenHandle = IntPtr.Zero;
235 |
236 | // Call LogonUser to obtain a handle to an access token.
237 | // If domain joined
238 | bool returnValue = LogonUser(userName, domainName, password, LOGON32_TYPE_NEW_CREDENTIALS,
239 | LOGON32_PROVIDER_WINNT50, ref tokenHandle);
240 |
241 |
242 | if (!returnValue)
243 | {
244 | int ret = Marshal.GetLastWin32Error();
245 | const int errorCode = 0x5; //ERROR_ACCESS_DENIED
246 | throw new System.ComponentModel.Win32Exception(errorCode);
247 | }
248 |
249 | returnValue = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
250 |
251 | if (!returnValue)
252 | {
253 | CloseHandle(tokenHandle);
254 | //Exception thrown in trying to duplicate token.
255 | return;
256 | }
257 |
258 | // The token that is passed to the following constructor must be a primary token in order to use it for impersonation.
259 | WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
260 | impersonatedUser = newId.Impersonate();
261 | }
262 |
263 | private void UnImpersonateUser()
264 | {
265 | if (impersonatedUser != null)
266 | {
267 | impersonatedUser.Undo();
268 | }
269 |
270 | if (tokenHandle != IntPtr.Zero)
271 | {
272 | CloseHandle(tokenHandle);
273 | }
274 |
275 | if (dupeTokenHandle != IntPtr.Zero)
276 | {
277 | CloseHandle(dupeTokenHandle);
278 | }
279 | }
280 | }
281 | }
282 |
--------------------------------------------------------------------------------