Beispiel #1
0
 void getInfoFromDs()
 {
     if (IsEnterprise && DsUtils.Ping())
     {
         if (_certConfig.GetField(CertConfigConstants.FieldCommonName) == Name)
         {
             String cn = "CN=" + _certConfig.GetField(CertConfigConstants.FieldSanitizedShortName) +
                         ",CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=Configuration,DC=" +
                         DsUtils.GetForestName().Replace(".", ",DC=");
             DistinguishedName = (String)DsUtils.GetEntryProperty(cn, DsUtils.PropDN);
             DisplayName       = _certConfig.GetField(CertConfigConstants.FieldCommonName);
             try {
                 String wes = _certConfig.GetField(CertConfigConstants.FieldEnrollmentServers);
                 if (!String.IsNullOrEmpty(wes))
                 {
                     getCesUri(wes);
                 }
             } catch { }
         }
     }
     if (String.IsNullOrEmpty(DisplayName))
     {
         DisplayName = Name;
     }
 }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the Oid2 class using the specified Oid friendly name or value, OID registration group and search conditions.
 /// </summary>
 /// <param name="oid">Specifies the object identifier friendly name or value to search.</param>
 /// <param name="group">Specifies the OID registration group to search.</param>
 /// <param name="searchInDirectory">Specifies whether to search for an object identifier in Active Directory. If the machine is not
 /// domain-joined, an OID is searched by using local registration information.</param>
 public Oid2(String oid, OidGroupEnum group, Boolean searchInDirectory)
 {
     try {
         CryptoConfig.EncodeOID(oid);
         _searchBy = "ByValue";
     } catch { _searchBy = "ByName"; }
     if (Environment.OSVersion.Version.Major >= 6)
     {
         _cng = true;
     }
     if (searchInDirectory)
     {
         if (DsUtils.Ping())
         {
             initializeDS(oid, group);
         }
         else
         {
             initializeLocal(oid, group);
         }
     }
     else
     {
         initializeLocal(oid, group);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Unregisters object identifier from OID registration database.
        /// </summary>
        /// <param name="value">Specifies the object identifier value.</param>
        /// <param name="group">Specifies the OID group from which the OID is removed. </param>
        /// <param name="deleteFromDirectory">
        ///		Specifies whether to perform registration removal from Active Directory. If Active Directory is unavailable,
        ///		the method will attempt to unregister OID from a local OID registration database.
        /// </param>
        /// <exception cref="ArgumentNullException"><strong>value</strong> parameter is null or empty.</exception>
        /// <returns>
        ///		<strong>True</strong> if OID or OIDs were unregistered successfully. If specified OID information is not
        ///		registered, the method returns <strong>False</strong>. An exception is thrown when caller do not have
        ///		appropriate permissions. See <strong>Remarks</strong> section for additional details.
        /// </returns>
        /// <remarks>
        /// <strong>Permissions:</strong> a caller must have local administrator permissions in order to remove OID
        /// registration from local OID database. When <strong>deleteFromDirectory</strong> is set to <strong>True</strong>,
        /// a caller must be a member of <strong>Enterprise Admins</strong> group or have delegated permissions on a OID
        /// container in Active Directory. OID container location is
        /// <i>CN=OID, CN=Public Key Services, CN=Services,CN=Configuration, {Configuration naming context}</i>.
        /// </remarks>
        public static Boolean Unregister(String value, OidGroupEnum group, Boolean deleteFromDirectory)
        {
            if (String.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(nameof(value));
            }
            List <Oid2> oids = new List <Oid2>();

            if (group == OidGroupEnum.AllGroups)
            {
                try { oids.AddRange(GetAllOids(value, deleteFromDirectory)); } catch { return(false); }
            }
            else
            {
                oids.Add(new Oid2(value, group, deleteFromDirectory));
                if (String.IsNullOrEmpty(oids[0].Value))
                {
                    return(false);
                }
            }
            if (!deleteFromDirectory || !DsUtils.Ping())
            {
                return(unregisterLocal(oids));
            }
            List <Int32> valid = new List <Int32>(new[] { 0, 7, 8, 9 });

            if (oids.Where(oid => !String.IsNullOrEmpty(oid.DistinguishedName)).Any(oid => oid.OidGroup != group && group != OidGroupEnum.AllGroups))
            {
                return(false);
            }
            return(valid.Contains((Int32)group) && unregisterDS(oids[0].Value, group));
        }
Beispiel #4
0
        /// <summary>
        /// Initializes a new instance of the Oid2 class using the specified Oid friendly name or value, OID registration group and search conditions.
        /// </summary>
        /// <param name="oid">Specifies the object identifier friendly name or value to search.</param>
        /// <param name="group">Specifies the OID registration group to search.</param>
        /// <param name="searchInDirectory">Specifies whether to search for an object identifier in Active Directory. If the machine is not
        /// domain-joined, an OID is searched by using local registration information.</param>
        public Oid2(String oid, OidGroupEnum group, Boolean searchInDirectory)
        {
            var flatOid = new Oid(oid);

            try {
                // try to validate if input OID contains OID value instead of friendly name
                Asn1Utils.EncodeObjectIdentifier(flatOid);
                oid       = flatOid.Value;
                _searchBy = "ByValue";
            } catch {
                _searchBy = "ByName";
            }

            if (Environment.OSVersion.Version.Major >= 6)
            {
                _cng = true;
            }
            if (searchInDirectory)
            {
                if (DsUtils.Ping())
                {
                    initializeDS(oid, group);
                }
                else
                {
                    initializeLocal(oid, group);
                }
            }
            else
            {
                initializeLocal(oid, group);
            }
        }
 public CertificateTemplate(String findType, String findValue)
 {
     if (!DsUtils.Ping())
     {
         throw new Exception(Error.E_DCUNAVAILABLE);
     }
     m_initialize(findType, findValue);
 }
Beispiel #6
0
 /// <summary>
 /// Initializes a new instance of <strong>DsPkiContainer</strong> class.
 /// </summary>
 /// <exception cref="PlatformNotSupportedException">
 /// The calling client is not a member of Active Directory domain or no domain controller can be contacted.
 /// </exception>
 protected DsPkiContainer()
 {
     if (!DsUtils.Ping())
     {
         throw new PlatformNotSupportedException();
     }
     _pkiConfigContext = $",CN=Public Key Services,CN=Services,{DsUtils.ConfigContext}";
 }
Beispiel #7
0
 /// <summary>
 /// Enumerates certificate templates registered in Active Directory.
 /// </summary>
 /// <returns>An array of certificate templates.</returns>
 public static CertificateTemplate[] EnumTemplates()
 {
     if (DsUtils.Ping())
     {
         String           cn      = _baseDsPath;
         DirectoryEntries entries = DsUtils.GetChildItems(cn);
         return((from DirectoryEntry item in entries select new CertificateTemplate("name", (String)item.Properties["cn"].Value)).ToArray());
     }
     throw new Exception(Error.E_DCUNAVAILABLE);
 }
Beispiel #8
0
        /// <summary>
        /// Registers object identifier in the OID database, either, local or in Active Directory.
        /// </summary>
        /// <param name="value">An object identifier value to register.</param>
        /// <param name="friendlyName">A friendly name associated with the object identifier.</param>
        /// <param name="group">Specifies the OID group where specified object identifier should be registered.</param>
        /// <param name="writeInDirectory">Specifies, whether object is registered locally or in Active Directory.</param>
        /// <param name="localeId">
        ///		Specifies the locale ID. This parameter can be used to provide localized friendly name. This parameter can
        ///		be used only when <strong>writeInDirectory</strong> is set to <strong>True</strong> in other cases it is
        ///		silently ignored.
        /// </param>
        /// <param name="cpsUrl">
        ///		Specifies the URL to a <i>certificate practice statement</i> (<strong>CPS</strong>) location.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///		<strong>value</strong> and/or <strong>friendlyName</strong> is null or empty.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///		Specified OID group is not supported. See <strong>Remarks</strong> section for more details.
        /// </exception>
        /// <exception cref="InvalidDataException"><strong>value</strong> parameter is not object idnetifier value.</exception>
        /// <exception cref="NotSupportedException">
        ///		A caller chose OID registration in Active Directory, however, the current computer is not a member of any
        ///		Active Directory domain.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///		An object identifier is already registered.
        /// </exception>
        /// <remarks>
        /// <para>
        /// <strong>Permissions:</strong> for this method to succeed, the caller must be a member of the local
        /// administrators group (if <strong>writeInDirectory</strong> is set to <strong>False</strong>) or
        /// be a member of <strong>Enterprise Admins</strong> group or has delegated write permissions on the
        /// <strong>OID</strong> container in Active Directory. OID container location is
        /// <i>CN=OID, CN=Public Key Services, CN=Services,CN=Configuration, {Configuration naming context}</i>.
        /// </para>
        /// <para>
        ///		A newly registered OID is not resolvable by an application immediately. You may need to restart an application
        ///		to allow new OID lookup.
        /// </para>
        /// <para>
        ///		When <strong>writeInDirectory</strong> is set to <strong>True</strong>, <strong>group</strong> parameter
        ///		is limited only to one of the following value: <strong>ApplicationPolicy</strong>,<strong>IssuancePolicy</strong>
        ///		and <strong>CertificateTemplate</strong>. Other OID groups are not allowed to be stored in Active Directory.
        /// </para>
        /// </remarks>
        /// <returns>Registered object identifier.</returns>
        public static Oid2 Register(String value, String friendlyName, OidGroupEnum group, Boolean writeInDirectory, CultureInfo localeId, String cpsUrl = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (String.IsNullOrEmpty(friendlyName))
            {
                throw new ArgumentNullException(nameof(friendlyName));
            }
            try {
                Asn1Utils.EncodeObjectIdentifier(new Oid(value));
            } catch {
                throw new InvalidDataException("The value is not valid OID string.");
            }

            String cn = null;

            if (writeInDirectory)
            {
                if (!DsUtils.Ping())
                {
                    throw new NotSupportedException("Workgroup environment is not supported.");
                }
                if (!String.IsNullOrEmpty(new Oid2(value, group, true).DistinguishedName))
                {
                    throw new InvalidOperationException("The object already exist.");
                }
                List <Int32> exclude = new List <Int32>(new[] { 0, 1, 2, 3, 4, 5, 6, 9, 10 });
                if (exclude.Contains((Int32)group))
                {
                    throw new ArgumentException("The OID group is not valid.");
                }
                registerDS(new Oid(value, friendlyName), group, localeId, cpsUrl);
                cn = "CN=" + computeOidHash(value) + ",CN=OID," + DsUtils.ConfigContext;
            }
            else
            {
                registerLocal(new Oid(value, friendlyName), group);
            }
            return(new Oid2 {
                FriendlyName = friendlyName,
                Value = value,
                OidGroup = group,
                DistinguishedName = cn
            });
        }
        static ICertConfigEntryD lookInDs(String computerName)
        {
            if (!DsUtils.Ping())
            {
                // we are in workgroup, so try to get DsEntry from whatever source we have using the name caller specified
                return(new CertConfigD().FindConfigEntryByServerName(computerName));
            }

            // we are connected to AD.
            // If name is passed in NetBIOS form, then translate to FQDN, because DS entries reference by FQDN only
            if (!computerName.Contains("."))
            {
                computerName = $"{computerName}.{DsUtils.GetCurrentDomainName()}";
            }
            // try to find by FQDN
            return(new CertConfigD().FindConfigEntryByServerName(computerName));
        }
        /// <summary>
        /// Enumerates certificate templates registered in Active Directory.
        /// </summary>
        /// <returns>An array of certificate templates.</returns>
        public static CertificateTemplate[] EnumTemplates()
        {
            if (!DsUtils.Ping())
            {
                throw new Exception(Error.E_DCUNAVAILABLE);
            }

            var retValue = new List <CertificateTemplate>();

            foreach (DirectoryEntry dsEntry in DsUtils.GetChildItems(_baseDsPath))
            {
                using (dsEntry) {
                    retValue.Add(FromCommonName(dsEntry.Properties["cn"].Value.ToString()));
                }
            }
            return(retValue.ToArray());
        }
        /// <summary>
        /// Enumerates registered in Certification Authorities from the current Active Directory forest.
        /// </summary>
        /// <param name="findType">Specifies CA object search type. The search type can be either: <strong>Name</strong>
        /// or <strong>Server</strong>.</param>
        /// <param name="findValue">Specifies search pattern for a type specified in <strong>findType</strong> argument.
        /// Wildcard characters: * and ? are accepted.</param>
        /// <returns>An array of Certification Authorities.</returns>
        public static CertificateAuthority[] EnumEnterpriseCAs(String findType = "Server", String findValue = "*")
        {
            if (!DsUtils.Ping())
            {
                throw new Exception("Non-domain environments are not supported.");
            }
            List <CertificateAuthority> CAs = new List <CertificateAuthority>();

            var certConfig = new CertConfigD();

            foreach (ICertConfigEntryD entry in certConfig.EnumConfigEntries())
            {
                if (!entry.Flags.HasFlag(CertConfigLocation.DsEntry))
                {
                    continue;
                }

                Wildcard wildcard = new Wildcard(findValue, RegexOptions.IgnoreCase);
                switch (findType.ToLower())
                {
                case "name":
                    if (!wildcard.IsMatch(entry.CommonName))
                    {
                        continue;
                    }
                    break;

                case "server":
                    if (!wildcard.IsMatch(entry.ComputerName))
                    {
                        continue;
                    }
                    break;

                default:
                    throw new ArgumentException("The value for 'findType' must be either 'Name' or 'Server'.");
                }
                CAs.Add(new CertificateAuthority(entry));
            }
            return(CAs.ToArray());
        }
Beispiel #12
0
        /// <summary>
        /// Enumerates registered Enterprise Certification Authorities from the current Active Directory forest.
        /// </summary>
        /// <param name="findType">Specifies CA object search type. The search type can be either: <strong>Name</strong>
        /// or <strong>Server</strong>.</param>
        /// <param name="findValue">Specifies search pattern for a type specifed in <strong>findType</strong> argument.
        /// Wildcard characters: * and ? are accepted.</param>
        /// <returns>Enterprise Certification Authority collection.</returns>
        public static CertificateAuthority[] EnumEnterpriseCAs(String findType, String findValue)
        {
            if (!DsUtils.Ping())
            {
                throw new Exception("Non-domain environments are not supported.");
            }
            List <CertificateAuthority> CAs = new List <CertificateAuthority>();
            CCertConfig certConfig          = new CCertConfig();

            while (certConfig.Next() >= 0)
            {
                Int32 flags = Convert.ToInt32(certConfig.GetField("Flags"));
                if ((flags & 1) == 0)
                {
                    continue;
                }
                Wildcard wildcard = new Wildcard(findValue, RegexOptions.IgnoreCase);
                switch (findType.ToLower())
                {
                case "name":
                    if (!wildcard.IsMatch(certConfig.GetField("CommonName")))
                    {
                        continue;
                    }
                    break;

                case "server":
                    if (!wildcard.IsMatch(certConfig.GetField("Server")))
                    {
                        continue;
                    }
                    break;

                default:
                    throw new ArgumentException("The value for 'findType' must be either 'Name' or 'Server'.");
                }
                CAs.Add(new CertificateAuthority(certConfig.GetField("Server"), certConfig.GetField("SanitizedName")));
            }
            CryptographyUtils.ReleaseCom(certConfig);
            return(CAs.ToArray());
        }
Beispiel #13
0
 void lookInDs(String computerName)
 {
     if (!DsUtils.Ping())
     {
         return;
     }
     if (!computerName.Contains("."))
     {
         computerName = computerName + "." + DsUtils.GetCurrentDomainName();
     }
     _certConfig.Reset(0); //TODO
     while (_certConfig.Next() >= 0)
     {
         Int32   flags           = Convert.ToInt32(_certConfig.GetField(CertConfigConstants.FieldFlags));
         Boolean serverNameMatch = String.Equals(_certConfig.GetField(CertConfigConstants.FieldServer), computerName, StringComparison.InvariantCultureIgnoreCase);
         if (serverNameMatch && (flags & 1) > 0)
         {
             foundInDs = true;
             return;
         }
     }
 }
Beispiel #14
0
 void getInfoFromDs()
 {
     if (IsEnterprise && DsUtils.Ping())
     {
         string domain = (string)DsUtils.GetEntryProperty(String.Join(".", this.ComputerName.Split('.').Where((v, i) => i != 0)) + "/RootDSE", "rootDomainNamingContext");
         String dn     = "CN=" + this.Name +
                         ",CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=Configuration," + domain;
         DistinguishedName = dn;
         DisplayName       = (String)DsUtils.GetEntryProperty(dn, "DisplayName");
         try {
             String wes = (String)DsUtils.GetEntryProperty(dn, "msPKI-Enrollment-Servers");
             if (!String.IsNullOrEmpty(wes))
             {
                 getCesUri(wes);
             }
         } catch { }
     }
     if (String.IsNullOrEmpty(DisplayName))
     {
         DisplayName = Name;
     }
 }