Example Management and Security Configuration Code

[Previous] [Next]

The following sections show how to administer different Microsoft technologies by using ADSI, WMI, and COM+. The technologies covered are Windows 2000, IIS, and SQL Server.

Windows 2000 Settings

The primary technologies for administering Windows 2000 are WMI and ADSI. All of the following samples are VBScript examples called from the WSH.

Retrieving computer information

The following code is useful for getting critical information from a possibly remote computer to determine its status. In this case, because the DomainRole value is 3, the code is returning computers acting as member servers. Table 13-1 defines other values for DomainRole.strServer = "."

 strQuery = & _ "Select * from Win32_ComputerSystem Where DomainRole = 3" Set compSet = & _ GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ strServer & "/root/Cimv2").ExecQuery(strQuery) For Each comp In compSet WScript.echo "Manufacturer: " & comp.Manufacturer WScript.echo "Model: " & comp.Model WScript.echo "Name: " & comp.Name WScript.echo "CPUs: " & comp.NumberOfProcessors WScript.echo "Owner: " & comp.PrimaryOwnerName WScript.echo "AdminPwdStat: " & comp.AdminPasswordStatus WScript.echo "DomainRole: " & comp.DomainRole For Each role in comp.Roles WScript.echo "Role: " & role Next Next 

Table 13-1. Possible WMI DomainRole values.

ValueDomain Role
0Stand-alone workstation
1Member workstation
2Stand-alone server
3Member server
4Backup domain controller
5Primary domain controller

Enumerating groups

The following WMI code will display all the groups on a computer:

 strServer = "." strQuery = "Select * from Win32_Group" Set grpSet = & _ GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ strServer & "/root/Cimv2").ExecQuery(strQuery) For Each grp In grpSet WScript.echo grp.Caption & " [SID=" & grp.SID & "]" Next 

Enumerating groups and users in the groups

The following code is a superset of the code in the previous section. It not only shows each group and the users in each group but also uses the WinNT: ADSI provider rather than WMI.

 strComputer = "MyServer" ' Use '.' for the local computer. Set oComp = GetObject("WinNT://" & strComputer & ",computer") oComp.Filter = Array("group") For Each group In oComp WScript.echo group.Name iCount = 0 For Each member in group.members WScript.echo " " & member.Name iCount = iCount + 1 Next If iCount = 0 Then WScript.echo " <none>" Next 

Viewing user account information

You can access user account information in many ways, including using the WMI provider, the LDAP provider, or the WinNT provider. The following code uses WMI to get a list of all locked-out accounts:

 strServer = "myserver" ' Use '.' to access the local computer. strQuery = "select * from Win32_UserAccount where Lockout = 0" Set userSet = & _ GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ strServer & "/root/Cimv2").ExecQuery(strQuery) For Each user In userSet WScript.echo user.Caption & " [" & user.SID & "]" Next 

This code uses the WinNT provider to list details about a specific account:

 strComputer = "remotecomputer" ' Use '.' for local computer. strUser = "administrator" Set oUser = GetObject("WinNT://" & strComputer & _ "/" & strUser & ",user") WScript.echo "Last Login: " & oUser.LastLogin WScript.echo "Member of..." For Each group in oUser.Groups WScript.echo " " & group.Name Next 

Accessing a user's certificate in Active Directory

The following ADSI example shows how to access a user's binary X.509 certificate. In this case, the user is cheryl@explorationair.com. Once you have the certificate, you can look at its contents by using the Certutil.exe tool described in Chapter 15, "An Introduction to Cryptography and Certificates in Windows 2000." Note that the userCertificate data is an array of bytes, so you might need to use another method other than the file system object (FSO), scripting.filesystemobject, to write out the data because FSO supports writing text only.

 strDomain = "DC=ExplorationAir,DC=com" strUser = "CN=Cheryl,CN=Users" Set user = GetObject("LDAP://" & strUser & "," & strDomain) cert = user.userCertificate 

Configuring the Account Is Sensitive And Cannot Be Delegated option

The following code shows a number of options that can be set on a user object in Active Directory, including Account Is Sensitive And Cannot Be Delegated:

 ACC_DISABLED = &H2 ACC_STORE_PWD_AS_CLEARTEXT = &H80 ACC_PWD_NEVER_EXPIRES = &H10000 ACC_SMARTCARD_REQUIREED = &H40000 ACC_TRUSTED_FOR_DELEGATION = &H80000 ACC_SENSITIVE = &H100000 StrDomain = "DC=explorationair,DC=com" StrUser = "CN=MichaelH,CN=Users" Set user = GetObject("LDAP://" & strUser & "," & strDomain) user.userAccountControl=user.userAccountControl Or & _ ACC_SENSITIVE user.SetInfo 

Changing a user's lockout property

It's not obvious how to read or set this property because the IsAccountLocked property is not accessible when using the LDAP provider—you must use the WinNT provider. The following code will read the lockout property by using the WinNT provider. If you want to set this property, you must call the SetInfo method on the oUser object after the property is set.

 Set oUser = GetObject("WinNT://EXAIR/cheryl") If oUser.IsAccountLocked Then Wscript.Echo "The account is locked out" End If 

Querying the Windows 2000 Security Event Log

The code following Table 13-2 uses WMI to query the Security Event Log on a remote computer to check whether any specific log entries have been written. In this case, we're searching for failed audit events that are not object access events (category 3). Note that TimeGenerated has an interesting format. It's not the number of seconds since a specific moment as in many other technologies—all dates and times in WMI use a fixed-length string. The string contains several fields:

 yyyymmddHHMMSS.mmmmmmsUUU 

Table 13-2 describes each of these fields. Note that an asterisk can be used in an unused field.

Table 13-2. WMI date string formats.

FieldComments
yyyyFour-digit year (0000-9999)
mmTwo-digit month (01-12)
ddTwo-digit date (01-31)
HHTwo-digit hours based on the 24-hour clock (00-23)
MMTwo-digit minute (00-59)
SSTwo-digit seconds (00-59)
mmmmmmSix-digit microseconds
s"+" or "-", indicating positive or negative offset from Universal Time Coordinate (UTC) (that is, Greenwich Mean Time)
UUUThree-digit offset from UTC in minutes

 strServer = "myserver" ' Use '.' for local computer. strQuery = "select * from Win32_NTLogEvent " & _ "where Logfile = 'Security' " & _ "and Type = 'audit failure' and Category <> 3" Set oLog = & _ GetObject("winmgmts:{impersonationLevel=impersonate}//" & _ strServer & "/root/Cimv2").ExecQuery(strQuery) For each oLogEntry in oLog WScript.Echo oLogEntry.Category WScript.Echo oLogEntry.TimeGenerated WScript.Echo oLogEntry.Message Next 

Internet Information Services 5 Settings

The main interface with IIS is ADSI, which is simply a wrapper on the lower-level COM+ metabase interface called IMSAdminBase. It's recommended that you use ADSI over the lower-level COM+ interface. Also, a tool exists called Adsutil.vbs in the InetPub\AdminScripts folder to set and enumerate all ADSI settings in IIS. For example, type the following at the command line to set the server comment on the default Web site to "ExAir Marketing.":

 cscript adsutil SET W3SVC/1/ServerComment "ExAir Marketing." 

You can view settings on the default Web site by typing

 adsutil enum W3SVC/1 

You can find out more about the use of ADSI in IIS in the IIS online help at http://localhost/iisHelp.

Configuring a Web site to require a secure connection

The following code shows how to set the "secure" virtual directory to require Secure Sockets Layer/Transport Layer Security (SSL/TLS):

 Set oIIS = GetObject("IIS://localhost/W3SVC/1/Secure") oIIS.AccessSSL = True ' True enables SSL. oIIS.AccessSSLFlags = AccessSSL128 ' Enable 128-bit crypto. oIIS.SetInfo Set oIIS = Nothing 

Configuring a Web virtual directory to require Windows authentication

The following sample code shows how to set Windows authentication on a virtual directory named Secure.

 Set oIIS = GetObject("IIS://localhost/W3SVC/1/Secure") ' Technically, this is wrong. Windows authentication ' could be NTLM or Kerberos. oIIS.AuthFlags = AuthNTLM oIIS.SetInfo Set oIIS = Nothing 

Enabling/disabling CRL checking on a Web server

This simple example sets the certificate revocation list (CRL) checking status on a default Web server, Web server #1:

 Set oIIS = GetObject("IIS://localhost/W3SVC/1") oIIS.CertCheckMode = True ' Set to False if you want ' to disable CRL checking. oIIS.SetInfo Set oIIS = Nothing 

Setting a different anonymous user account on a virtual directory

This example code shows how you can set the anonymous user account to be a specific account on a virtual directory named Pricelist on the default Web server:

 Set oIIS = GetObject("IIS://localhost/W3SVC/1/Pricelist") oIIS.AnonymousUserName = "PriceListAnonUser" oIIS.AnonymousUserPass = "WeakPassword1" oIIS.SetInfo Set oIIS = Nothing 

Setting a logon type for Basic authentication users

The following sample shows how you can set the logon type for Basic authentication on a remote computer named \\merlin. This setting is the value IIS uses when it calls LogonUser internally. Note that the accounts logging on must have the privilege you chose or they will not be able to log on.

The default setting is LOGON_LOCAL. If you select LOGON_NETWORK_CLEARTEXT, the account will have the much more secure network logon privilege yet will still be able to access remote resources when using NTLM authentication rather than Kerberos. This will happen if the Web servers are not running in a Windows 2000 domain.

Note also that the constants defined in the code are not the same as the constants used in the call to LogonUser.

 Dim oIIS Const LOGON_LOCAL = 0x0 Const LOGON_BATCH = 0x1 Const LOGON_NETWORK = 0x2 Const LOGON_NETWORK_CLEARTEXT = 0x3 Set oIIS = GetObject("IIS://Merlin/W3SVC/1") oIIS.LogonMethod = LOGON_BATCH oIIS.SetInfo Set oIIS=Nothing 

Setting IP restrictions

The following code shows how to set IP restrictions on the Secure virtual directory on the default Web server such that only localhost (127.0.0.1) can access its resources:

 ' Get the IP Settings. Set oVDir = GetObject("IIS://localhost/W3SVC/1/Secure") Set oIP = oVDir.IPSecurity ' Set the IP grant list to 127.0.0.1. Dim IPList(1) IPList(1) = "127.0.0.1" oIP.IPGrant = IPList ' Do not grant access by default. oIP.GrantByDefault = 0 ' Write the information back to ' Internet Information Services and clean up. oVDir.IPSecurity = oIP oVDir.SetInfo Set oIP = Nothing Set oVDir = Nothing 

SQL Server 7 and SQL Server 2000 Settings

SQL Distributed Management Object (SQL-DMO) is a collection of COM+ objects for administering SQL Server from programming and scripting languages. The most complete documentation can be found in the Microsoft SQL Server Books Online documentation.

Enumerating databases and tables

The following example shows how you can display all databases and tables on an instance of SQL Server, as well as the effective privileges and the row count of each table:

 Set oSQL = CreateObject("SQLDMO.SQLServer") oSQL.LoginSecure = true ' Use Windows authentication. oSQL.LoginTimeout = 30 oSQL.Connect "dbserver" ' Use '.' to represent local ' computer. For i = 1 to oSQL.Databases.Count Set oDB = oSQL.Databases(i) WScript.echo oDb.Name For j = 1 to oDB.Tables.Count Set oT = oDB.Tables(j) If oT.Attributes <> 2 Then ' 2 == System object. WScript.echo " " & oT.Name & " (" & oT.Rows & ")" Set oPerm = oT.ListPermissions() For each p in oPerm WScript.echo " " & p.PrivilegeTypeName Next End If Next Next 

Adding a new login to SQL Server

The following code shows how to use SQL-DMO to add a new login to SQL Server. The account added can be a SQL Server account or a Windows account. If you're adding a Windows account, you must provide the domain name and username.

 Set oSQL = CreateObject("SQLDMO.SQLServer") oSQL.LoginSecure = true ' Use Windows authentication. oSQL.LoginTimeout = 30 oSQL.Connect "." ' Use '.' to represent local computer. For i = 1 to oSQL.Logins.Count WScript.echo oSQL.Logins(i).Name Next Set oLogin = CreateObject("SQLDMO.Login") oLogin.Name = "EXAIR\Cheryl" oLogin.Type = 0 ' 0 = Windows account, 2 = SQL account. oSQL.Logins.Add(oLogin) 

Adding a login to a SQL Server role

The following example adds a user named Bob to the Security Administrators role:

 Set oSQL = CreateObject("SQLDMO.SQLServer") oSQL.LoginSecure = true ' Use Windows authentication. oSQL.LoginTimeout = 30 oSQL.Connect "dbserver" ' Use '.' to represent local ' computer. Set oRole = oSQL.ServerRoles("SecurityAdmin") WScript.echo oRole.FullName ' The Logon 'Bob' must already exist in SQL Server. oRole.AddMember("Bob") 

Miscellaneous COM+ Scripts

In this section, we'll describe two other ways you can use COM+ and script to administer your computers.

Querying security settings in the COM+ Catalog

COM+ exposes copious information in the COM+ Catalog—a combination of the Registry and the RegDB database that functions as a single logical entity—about COM+ applications. The following script displays relevant security information about all the applications on the current computer:

 ' Open the catalog and access the application data. Set oCatalog = CreateObject("COMAdmin.COMAdminCatalog") Set oApplications = oCatalog.GetCollection("Applications") oApplications.Populate Header TAB = Chr(9) For Each oApp In oApplications ' Get the settings. iAppChecks = oApp.Value("ApplicationAccessChecksEnabled") iAuth = oApp.Value("Authentication") iAuthCap = oApp.Value("AuthenticationCapability") iImp = oApp.Value("ImpersonationLevel") strInfo = GetAuth(iAuth) & TAB & _ GetAuthCap(iAuthCap) & TAB & _ GetImp(iImp) & TAB & _ iAppChecks & TAB & _ oApp.Name WScript.Echo strInfo Next Function GetAuthCap(iAuthCap) strAuthCap = "Unknown " Select Case iAuthCap Case &h00 : strAuthCap = "None" Case &h02 : strAuthCap = "Cloak" Case &h20 : strAuthCap = "DynCloak" Case &h40 : strAuthCap = "Reference" End Select GetAuthCap = strAuthCap End Function Function GetAuth(iAuth) strAuth = "Unknown" Select Case iAuth Case 0 : strAuth = "Default" Case 1 : strAuth = "None" Case 2 : strAuth = "Connect" Case 3 : strAuth = "Call" Case 4 : strAuth = "Packet" Case 5 : strAuth = "Intgrty" Case 6 : strAuth = "Privacy" End Select GetAuth = strAuth End Function Function GetImp(iImp) strImp = "Unknown" Select Case iImp Case 1 : strImp = "Anonymous " Case 2 : strImp = "Identify " Case 3 : strImp = "Impersonate" Case 4 : strImp = "Delegate " End Select GetImp = strImp End Function Function Header WScript.Echo "---------------------------------------" & _ "-----------------------------" WScript.Echo "Auth Auth Impersonate App" WScript.Echo "Type Cap's Level " & _ " Checks Name" WScript.Echo "---------------------------------------" & _ "-----------------------------" End Function 

Determining whether a server has a "heartbeat"

The following script uses Windows Sockets (Winsock) to ping a server at regular intervals. If the server at the specified IP address is listening and replies within the predetermined timeframe, the server is considered to have a "heartbeat"—that is, to be "alive and functioning."

 Dim iProtocol, iPort, dwSleep, strIP strIP = Array("157.59.133.192", "157.59.133.193") iProtocol = 0 ' TCP. iPort = 80 dwSleep = 2000 ' 2 seconds. Set o = CreateObject("MSWinsock.Winsock") o.Protocol = iProtocol Do For i = LBound(strIP) To UBound(strIP) o.Connect strIP(i), iPort WScript.Sleep dwSleep strDetail = strIP(i) & " is " If o.State = 9 Then strDetail = strDetail & "Dead" If o.State = 7 Then strDetail = strDetail & "Listening" strDetail = strDetail & " on " & iPort WScript.echo strDetail o.Close Next Loop 

Common IIS Security-Related ADSI Settings

Table 13-3 lists common security-related ADSI properties and objects used in IIS 5. Where applicable, the hexadecimal value of a setting is provided.

Table 13-3. Security-related IIS ADSI values.

Setting/ObjectComments
AccessFlags This setting determines the type of access to a Web resource. Valid settings are AccessExecute (0x4), AccessNoRemoteExecute (0x2000), AccessNoRemoteRead (0x1000), AccessNoRemoteScript (0x4000), AccessNoRemoteWrite (0x400), AccessRead (0x1) (the default setting), AccessScript (0x200), AccessSource (0x10), and AccessWrite (0x2).
AccessScript allows Active Server Pages (ASP) pages to run. If set, the AccessSource flag grants source access to users, using the Web-based Distributed Authoring and Versioning (WebDAV) HTTP extensions.
Remote access flags are valid only when the corresponding general access flag is set. For example, setting AccessNoRemoteRead has no effect unless AccessRead is set as well. If both are set, the local host can read the file, but the file cannot be read by the remote client.
There is no way of setting the AccessNoXxx settings other than through ADSI; they are not available in the IIS administration tools.
AccessSSLFlags This setting contains SSL/TLS requirements. Valid options are AccessSSL (0x8), AccessSSL128 (0x100), AccessSSLMapCert (0x80), AccessSSLNegotiateCert (0x20), and AccessSSLRequireCert (0x40).
If set, AccessSSL requires an SSL/TLS connection. AccessSSL128 requires that the connection be 128-bit. AccessSSLNegotiateCert will request a client authentication certificate from the client but not require one. AccessSSLRequireCert requires the client to provide a certificate.
Note that to require a client authentication certificate you must set AccessSSLFlags to AccessSSLNegotiateCert + AccessSSLRequireCert.
AccessSSLMapCert will map the provided client authentication certificate. To use this option, AccessSSLFlags must be set to AccessSSLNegotiateCert + AccessSSLMapCert. Refer to SSLUseDsMapper for more information about which certificate mapper is used: the IIS mapper or the Active Directory mapper.
AdminACL This setting determines what access users have to the metabase. It is recommended that this not be changed.
AllowSpecialCharsInShell This Registry value controls whether special characters (including | ( , ; % < and >) are allowed when running batch files (.bat and .cmd files). These special characters can pose a serious security risk. If the value of this entry is set to 1, malicious users can execute commands on the server.
The setting can be found at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters.
AnonymousPasswordSync This property indicates whether IIS should handle the user password for anonymous users attempting to access resources. See also AnonymousUserName and AnonymousUserPass.
AnonymousUserName Sets the username for unauthenticated access to a Web resource. See also AnonymousUserPass and AnonymousPasswordSync.
AnonymousUserPass Sets the password for the account used for unauthenticated access to a Web resource. See also AnonymousUserName and AnonymousPasswordSync.
AuthFlags This property contains the authentication protocols supported when accessing a Web resource. Values include AuthAnonymous (0x1), AuthBasic (0x2), AuthMD5 (0x10), and AuthNTLM (0x4).
AuthMD5 is Digest authentication. AuthNTLM is the Negotiate protocol; it will use either NTLM or Kerberos. Note that AuthMD5 is not in the IIS online documentation.
AuthPersistence This property specifies authentication persistence across requests on a connection. Valid options are AuthPersistSingleRequest (0x40), AuthPersistSingleRequestIfProxy (0x80) (the default value), and AuthPersistSingleRequestAlwaysIfProxy (0x100).
If AuthPersistSingleRequest is set, authentication persists for a single connection. AuthPersistSingleRequestIfProxy is the same as the above setting but only if the request is handled by a non-Microsoft proxy server. AuthPersistSingleRequestAlwaysIfProxy is the same as the above setting but for all proxy requests.
CertCheckMode Determines whether to check the CRL associated with a Web browser. The default, 0, is to check for certificate revocation, while a nonzero value will not check for a CRL.
CheckCertRevocation This Registry setting works with CertCheckMode and is used only when a Web server is upgraded from Internet Information Server 4. CheckCertRevocation overrides CertCheckMode if CheckCertRevocation is set to True. By default, it is False.
The setting can be found at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\InetInfo\Parameters.
CreateProcessAsUser This property specifies whether a Common Gateway Interface (CGI) process will be created in the system context or in the context of the requesting user. The default value is True and should not be changed.
DefaultLogonDomain This property specifies the default domain for logon when using Basic or Digest authentication. If this value is not specified (the default), the default domain will be the domain name in which the Web server resides. If the computer is not in a domain, the default domain will be the computer name.
IIsCertMapper (object) The IIsCertMapper object allows the ASP developer to write code to map X.509 client authentication certificates on to Windows 2000 user accounts.
IPSecurity (object) The IPSecurity object allows the ASP developer to write code that imposes IP and DNS restrictions. Do not confuse this setting with Internet Protocol Security (IPSec), built into Windows 2000.
LogonMethod This property specifies the logon method used for accounts logging on with Basic authentication. Valid settings are logon locally (0), logon as a batch job (1), network logon (2), and network logon with cleartext (3). Note that the last setting is not in the IIS online documentation.
NTAuthenticationProviders This property contains a comma-delimited list of Windows authentication providers used by the Web service. This is also the list of authentication methods sent to a browser during an HTTP 401 error. Its default value is Negotiate,NTLM.
ProcessNTCRIfLoggedOn This property enables processing of Integrated Windows (NTLM) authentication even if a user has already logged on using an alternate authentication scheme. The default value is True.
Realm This property specifies the realm when the server requests that the client authenticate itself using Basic or Digest authentication. The default value is "", which sets the realm name to the name of the server.
SecureBindings This property specifies a string that is used by IIS to determine which SSL/TLS IP addresses and ports to listen on. The format of the string is IPAddress:Port:.
If IPaddress is missing, all IP addresses are assumed. The default value is :443: when SSL/TLS is enabled.
SSLCertHash The hash of the certificate used when SSL/TLS is enabled. You can determine the hash of a certificate by looking at the certificate's thumbprint in the Certificate Properties box. Note that SSLCertHash is a binary value and cannot be set using ADSI from scripting languages—you must use a language like C++.
SSLStoreName The name of the certificate store that holds the server's SSL/TLS certificate and private key. By default, this is My, and there's no reason to change it.
SSLUseDsMapper This property specifies whether IIS uses the Active Directory Service certificate mapper or the IIS certificate mapper. The default value, False, means IIS certificate mapping will be used.
UNCAuthenticationPassthrough This property enables user authentication pass-through for Universal Naming Convention (UNC) virtual root access when using delegable authentication protocols such as Kerberos.
UNCPassword This property specifies the encrypted password used to gain access to UNC virtual roots when not using a delegable authentication protocol such as Kerberos.
UNCUserName This property specifies the username used to gain access to UNC virtual roots when not using a delegable authentication protocol such as Kerberos.
UserTokenTTL

This Registry setting determines how long to cache a user's token once the user has logged on to IIS. Applies to non-Windows authentication protocols only. The default is 15 minutes, but for debugging purposes it's worthwhile to set it to 0.

The value can be found at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\InetInfo\Parameters.

WAMUserName This property specifies the account name that IIS uses by default as the COM+ application identity for newly created Web applications requiring Medium or High protection. The default value is IWAM_machinename.
WAMUserPass This property specifies the password that IIS uses by default as the COM+ application identity for newly created Web applications requiring Medium or High protection. The default value is generated when IIS is installed.



Designing Secure Web-Based Applications for Microsoft Windows 2000 with CDROM
Designing Secure Web-Based Applications for Microsoft Windows 2000 with CDROM
ISBN: N/A
EAN: N/A
Year: 1999
Pages: 138

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net