/// <summary>
        /// Create a new bucket with the specified parameters. If it already exists, return the bucket details.
        /// Requires bucket:create scope
        /// </summary>
        /// <param name="bucketKey"></param>
        /// <param name="policyKey"></param>
        /// <param name="region"></param>
        /// <returns></returns>
        public async Task <BucketDetails> CreateBucketAsync(string bucketKey, PolicyKey policyKey, Region region = Region.US)
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.AddHeader(PredefinedHeadersExtension.PredefinedHeaders.ContentTypeJson);
            headers.Add("x-ads-region", Enum.GetName(typeof(Region), region));

            var body = new { bucketKey = bucketKey, policyKey = Enum.GetName(typeof(PolicyKey), policyKey).ToLower() };

            IRestResponse res = await REST.MakeAuthorizedRequestAsync(Authorization, END_POINTS.POST_BUCKETS, Method.POST, headers, null, body);

            if (res.StatusCode != System.Net.HttpStatusCode.OK && res.StatusCode != System.Net.HttpStatusCode.Conflict)
            {
                throw new Exception(string.Format("Endpoint {0} at Buckets.CreateBucket returned {1}", Internal.END_POINTS.GET_BUCKETS, res.StatusCode));
            }

            BucketDetails newBucket;

            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                newBucket = new BucketDetails(Authorization);
                JsonConvert.PopulateObject(res.Content, newBucket);
            }
            else // Conflict: bucket already exists, but we need to honor the expected return
            {
                newBucket = await BucketDetails.InitializeAsync(Authorization, bucketKey);
            }

            return(newBucket);
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            const string policyKeyStringMs = @"SOFTWARE\Policies\Microsoft";
            const string policyKeyString   = @"SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services";

            Microsoft.Win32.RegistryKey PolicyKey;

            // Create policy reg keys
            var policyKeyMs  = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(policyKeyStringMs, true);
            var policyKeyWnt = policyKeyMs.CreateSubKey("Windows NT");

            _         = policyKeyWnt.CreateSubKey("Terminal Services");
            PolicyKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(policyKeyString, true);
            if (DisableAllowListCheckBox.Checked)
            {
                Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\TSAppAllowList", "fDisabledAllowList", "1", Microsoft.Win32.RegistryValueKind.DWord);
            }
            else
            {
                Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\TSAppAllowList", "fDisabledAllowList", "0", Microsoft.Win32.RegistryValueKind.DWord);
            }

            if (AllowUnlistedRemoteProgramsCheckBox.Checked)
            {
                PolicyKey.SetValue("fAllowUnlistedRemotePrograms", 1, Microsoft.Win32.RegistryValueKind.DWord);
            }
            else
            {
                PolicyKey.DeleteValue("fAllowUnlistedRemotePrograms", false);
            }

            if (TimeoutDisconnectedCheckBox.Checked)
            {
                PolicyKey.SetValue("MaxDisconnectionTime", double.Parse(DisconnectTimeTextBox.Text) * 1000d, Microsoft.Win32.RegistryValueKind.DWord);
            }
            else
            {
                PolicyKey.DeleteValue("MaxDisconnectionTime", false);
            }

            if (TimeoutIdleCheckBox.Checked)
            {
                PolicyKey.SetValue("MaxIdleTime", double.Parse(IdleTimeTextBox.Text) * 1000d, Microsoft.Win32.RegistryValueKind.DWord);
            }
            else
            {
                PolicyKey.DeleteValue("MaxIdleTime", false);
            }

            if (LogoffWhenTimoutCheckBox.Checked)
            {
                PolicyKey.SetValue("fResetBroken", "1", Microsoft.Win32.RegistryValueKind.DWord);
            }
            else
            {
                PolicyKey.DeleteValue("fResetBroken", false);
            }

            Close();
        }
Beispiel #3
0
        // This function sends the request and returns
        // the response.
        public ASCommandResponse GetResponse()
        {
            GenerateXMLPayload();

            if (Credentials == null || Server == null || ProtocolVersion == null || WbxmlBytes == null)
            {
                throw new InvalidDataException("ASCommandRequest not initialized.");
            }

            // Generate the URI for the request
            string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync?{2}",
                                             useSSL ? "https:" : "http:", server, RequestLine);
            Uri             serverUri = new Uri(uriString);
            CredentialCache creds     = new CredentialCache();

            // Using Basic authentication
            creds.Add(serverUri, "Basic", credential);

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);

            httpReq.Credentials = creds;
            httpReq.Method      = "POST";

            // MS-ASHTTP section 2.2.1.1.2.2
            httpReq.ContentType = "application/vnd.ms-sync.wbxml";

            if (!UseEncodedRequestLine)
            {
                // Encoded request lines include the protocol version
                // and policy key in the request line.
                // Non-encoded request lines require that those
                // values be passed as headers.
                httpReq.Headers.Add("MS-ASProtocolVersion", ProtocolVersion);
                httpReq.Headers.Add("X-MS-PolicyKey", PolicyKey.ToString());
            }

            try
            {
                Stream requestStream = httpReq.GetRequestStream();
                requestStream.Write(WbxmlBytes, 0, WbxmlBytes.Length);
                requestStream.Close();

                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

                ASCommandResponse response = WrapHttpResponse(httpResp);

                httpResp.Close();

                return(response);
            }
            catch (Exception ex)
            {
                ASError.ReportException(ex);
                return(null);
            }
        }
		internal void AddSerializedPolicies (StreamReader reader)
		{
			if (policies == null)
				policies = new PolicyDictionary ();
			foreach (ScopedPolicy policyPair in PolicyService.RawDeserializeXml (reader)) {
				PolicyKey key = new PolicyKey (policyPair.PolicyType, policyPair.Scope);
				if (policies.ContainsKey (key))
					throw new InvalidOperationException ("Cannot add second policy of type '" +  
					                                     key.ToString () + "' to policy set '" + Id + "'");
				policies[key] = policyPair.Policy;
				if (!policyPair.SupportsDiffSerialize)
					externalPolicies.Add (key);
			}
		}
Beispiel #5
0
        public ASCommandResponse GetResponse()
        {
            GenerateXMLPayload();

            if (Credentials == null || Server == null || ProtocolVersion == null || WbxmlBytes == null)
            {
                throw new InvalidDataException("ASCommandRequest not initialized.");
            }

            string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync?{2}",
                                             useSSL ? "https:" : "http:", server, RequestLine);
            Uri             serverUri = new Uri(uriString);
            CredentialCache creds     = new CredentialCache();

            // Using Basic authentication
            creds.Add(serverUri, "Basic", credential);

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);

            httpReq.Credentials = creds;
            httpReq.Method      = "POST";
            httpReq.ContentType = "application/vnd.ms-sync.wbxml";

            if (!UseEncodedRequestLine)
            {
                httpReq.Headers.Add("MS-ASProtocolVersion", ProtocolVersion);
                httpReq.Headers.Add("X-MS-PolicyKey", PolicyKey.ToString());
            }

            try
            {
                Stream requestStream = httpReq.GetRequestStream();
                requestStream.Write(WbxmlBytes, 0, WbxmlBytes.Length);
                requestStream.Close();

                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

                ASCommandResponse response = WrapHttpResponse(httpResp);

                httpResp.Close();

                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #6
0
        // This function generates the XML request body
        // for the Provision request.
        protected override void GenerateXMLPayload()
        {
            // If WBXML was explicitly set, use that
            if (WbxmlBytes != null)
            {
                return;
            }

            // Otherwise, use the properties to build the XML and then WBXML encode it
            XmlDocument provisionXML = new XmlDocument();

            XmlDeclaration xmlDeclaration = provisionXML.CreateXmlDeclaration("1.0", "utf-8", null);

            provisionXML.InsertBefore(xmlDeclaration, null);

            XmlNode provisionNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "Provision", Namespaces.provisionNamespace);

            provisionNode.Prefix = Xmlns.provisionXmlns;
            provisionXML.AppendChild(provisionNode);

            // If this is a remote wipe acknowledgment, use
            // the remote wipe acknowledgment format
            // specified in MS-ASPROV section 3.1.5.1.2.2.
            if (isRemoteWipe)
            {
                // Build response to RemoteWipe request
                XmlNode remoteWipeNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "RemoteWipe", Namespaces.provisionNamespace);
                remoteWipeNode.Prefix = Xmlns.provisionXmlns;
                provisionNode.AppendChild(remoteWipeNode);

                // Always return success for remote wipe
                XmlNode statusNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "Status", Namespaces.provisionNamespace);
                statusNode.Prefix    = Xmlns.provisionXmlns;
                statusNode.InnerText = "1";
                remoteWipeNode.AppendChild(statusNode);
            }

            // The other two possibilities here are
            // an initial request or an acknowledgment
            // of a policy received in a previous Provision
            // response.
            else
            {
                if (!isAcknowledgement)
                {
                    // A DeviceInformation node is only included in the initial
                    // request.
                    XmlNode deviceNode = provisionXML.ImportNode(provisionDevice.GetDeviceInformationNode(), true);
                    provisionNode.AppendChild(deviceNode);
                }

                // These nodes are included in both scenarios.
                XmlNode policiesNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "Policies", Namespaces.provisionNamespace);
                policiesNode.Prefix = Xmlns.provisionXmlns;
                provisionNode.AppendChild(policiesNode);

                XmlNode policyNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "Policy", Namespaces.provisionNamespace);
                policyNode.Prefix = Xmlns.provisionXmlns;
                policiesNode.AppendChild(policyNode);

                XmlNode policyTypeNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "PolicyType", Namespaces.provisionNamespace);
                policyTypeNode.Prefix    = Xmlns.provisionXmlns;
                policyTypeNode.InnerText = policyType;
                policyNode.AppendChild(policyTypeNode);

                if (isAcknowledgement)
                {
                    // Need to also include policy key and status
                    // when acknowledging
                    XmlNode policyKeyNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "PolicyKey", Namespaces.provisionNamespace);
                    policyKeyNode.Prefix    = Xmlns.provisionXmlns;
                    policyKeyNode.InnerText = PolicyKey.ToString();
                    policyNode.AppendChild(policyKeyNode);

                    XmlNode statusNode = provisionXML.CreateElement(Xmlns.provisionXmlns, "Status", Namespaces.provisionNamespace);
                    statusNode.Prefix    = Xmlns.provisionXmlns;
                    statusNode.InnerText = status.ToString();
                    policyNode.AppendChild(statusNode);
                }
            }

            StringWriter  stringWriter = new StringWriter();
            XmlTextWriter xmlWriter    = new XmlTextWriter(stringWriter);

            xmlWriter.Formatting = Formatting.Indented;
            provisionXML.WriteTo(xmlWriter);
            xmlWriter.Flush();

            XmlString = stringWriter.ToString();
        }
Beispiel #7
0
        public ASCommandResponse GetResponse()
        {
            string StatusCode = string.Empty;
            string Meaning    = string.Empty;
            string Cause      = string.Empty;
            string Resolution = string.Empty;

            EASTester.EasHelp oHelp = new EASTester.EasHelp();

            GenerateXMLPayload();

            //if (ProtocolVersion == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Protocol version not specified.");

            //if (ProtocolVersion == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - EAS Protocol version must be set");

            //if (WbxmlBytes == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Request is empty.");

            //if (Server == null)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Server must be specified.");

            //if (Credentials == null && useCertificateAuthentication == false)
            //    throw new InvalidDataException("ASCommandRequest not initialized for authentication.");

            //if (useCertificateAuthentication == true && certificateFile.Length == 0)
            //    throw new InvalidDataException("ASCommandRequest not initialized - Certificate file must be specified.");

            string uriString = string.Format("{0}//{1}/Microsoft-Server-ActiveSync?{2}",
                                             useSSL ? "https:" : "http:", server, RequestLine);
            Uri serverUri = new Uri(uriString);

            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uriString);

            //httpReq.ClientCertificates.
            httpReq.Method      = "POST";
            httpReq.ContentType = "application/vnd.ms-sync.wbxml";

            // Handle any certificate errors on the certificate from the server.
            //ServicePointManager.CertificatePolicy = new CertPolicy();

            //bool bSettingCredsWasOK = false;
            if (useCertificateAuthentication == true)
            {
                // https://support.microsoft.com/en-us/kb/895971
                try
                {
                    httpReq.UseDefaultCredentials = false;
                    X509Certificate oX509Certificate = null;

                    //oX509Certificate = new X509Certificate.CreateFromCertFile(certificateFile);

                    oX509Certificate = new X509Certificate(certificateFile, certificatePassword);
                    httpReq.ClientCertificates.Add(oX509Certificate);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error setting certificate authentication.");
                    return(null);
                }
            }
            else
            {
                try
                {
                    CredentialCache creds = new CredentialCache();
                    creds.Add(serverUri, "Basic", credential);  // Using Basic authentication
                    httpReq.Credentials = creds;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error setting specified credentials.");
                    return(null);
                }
            }



            if (SpecifyProxySettings == true)
            {
                WebProxy oWebProxy = null;
                oWebProxy = new WebProxy(ProxyServer, ProxyPort);
                //oWebProxy.BypassProxyOnLocal = BypassProxyForLocalAddress;

                if (OverrideProxyCredntials == true)
                {
                    if (ProxyUser.Trim().Length == 0)
                    {
                        oWebProxy.UseDefaultCredentials = true;
                    }
                    else
                    {
                        if (ProxyDomain.Trim().Length == 0)
                        {
                            oWebProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword);
                        }
                        else
                        {
                            oWebProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword, ProxyDomain);
                        }
                    }
                }
                else
                {
                    oWebProxy.UseDefaultCredentials = true;
                }

                httpReq.Proxy = oWebProxy;
            }

            if (UserAgent.Trim().Length != 0)
            {
                httpReq.UserAgent = UserAgent;
            }

            if (!UseEncodedRequestLine)
            {
                httpReq.Headers.Add("MS-ASProtocolVersion", ProtocolVersion);
                httpReq.Headers.Add("X-MS-PolicyKey", PolicyKey.ToString());
            }

            try
            {
                Stream requestStream = httpReq.GetRequestStream();
                requestStream.Write(WbxmlBytes, 0, WbxmlBytes.Length);
                requestStream.Close();

                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();

                //float iisStatusCode = (float)httpResp.StatusCode;


                ASCommandResponse response = WrapHttpResponse(httpResp);

                httpResp.Close();

                //StatusCode = iisStatusCode.ToString();
                //Meaning = string.Empty;
                //Cause = string.Empty;
                //Resolution = string.Empty;
                //oHelp.GetHttpStatusInfo(StatusCode, ref Meaning, ref Cause, ref Resolution);

                //MessageBox.Show("IIS Resposne Code: " + StatusCode + "\r\nDescription: " + Meaning);

                return(response);
            }
            catch (WebException wex)
            {
                MessageBox.Show("Exception: \r\n" + wex.ToString(), "Error");

                return(null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: \r\n" + ex.ToString(), "Error");

                return(null);
            }
        }
Beispiel #8
0
		internal void LoadFromXml (XmlReader reader)
		{
			if (policies == null)
				policies = new PolicyDictionary ();
			else
				policies.Clear ();
			
			reader.MoveToContent ();
			string str = reader.GetAttribute ("name");
			if (!string.IsNullOrEmpty (str))
				Name = str;
			str = reader.GetAttribute ("id");
			if (!string.IsNullOrEmpty (str))
				Id = str;
			reader.MoveToElement ();
			
			//note: can't use AddSerializedPolicies as we want diff serialisation
			foreach (ScopedPolicy policyPair in PolicyService.DiffDeserializeXml (reader)) {
				PolicyKey key = new PolicyKey (policyPair.PolicyType, policyPair.Scope);
				if (policies.ContainsKey (key))
					throw new InvalidOperationException ("Cannot add second policy of type '" +  
					                                     key.ToString () + "' to policy set '" + Id + "'");
				policies[key] = policyPair.Policy;
			}
		}
Beispiel #9
0
		internal bool SupportsDiffSerialize (ScopedPolicy pol)
		{
			if (!AllowDiffSerialize)
				return false;
			PolicyKey pk = new PolicyKey (pol.PolicyType, pol.Scope);
			return !externalPolicies.Contains (pk);
		}
		internal void LoadFromFile (StreamReader reader)
		{
			if (policies == null)
				policies = new PolicyDictionary ();
			else
				policies.Clear ();
			
			//note: can't use AddSerializedPolicies as we want diff serialisation
			foreach (ScopedPolicy policyPair in PolicyService.DiffDeserializeXml (reader)) {
				PolicyKey key = new PolicyKey (policyPair.PolicyType, policyPair.Scope);
				if (policies.ContainsKey (key))
					throw new InvalidOperationException ("Cannot add second policy of type '" +  
					                                     key.ToString () + "' to policy set '" + Id + "'");
				policies[key] = policyPair.Policy;
			}
		}