Friday, April 26, 2019

AWS Config Service Organization-Wide Member Account Config Aggregator

Source code and download: https://github.com/walkerk1980/AWSConfigOrgsMemberAccountAggregator

The reason that you may want to use this script - The AWS Config Service offers an option that integrates with AWS Organizations that have 'All Features' enabled to automatically create a Configuration Aggregator in your Organizations Master Account that aggregates all of your Member Accounts in all supported AWS Regions. This aggregator can only be created in the Master Account of the Organization. It is not possible to use the AWS Provided method to create an Organization-wide Aggregator in one of your Member Accounts, say for example, your account designated for Security or Monitoring. [1] 
[1] Multi-Account Multi-Region Data Aggregation - https://docs.aws.amazon.com/config/latest/developerguide/aggregate-data.html
The purpose of this script is to create a Config Aggregator in an Organizations Member Account that Aggregates all of your Organization's Member Accounts across all supported Regions. Normally this requires Creating an Aggregator in one of your Member Account and inviting all of the Accounts in your Organization. This would then require signing in to each Member Account in your Organization and adding an Authorization for the Aggregator Account. This script automates that process by assuming the Organizations Access Roles of each of your Member Accounts to create the Config Aggregator and to Authorize the Aggregator in the Master Account as well as all of the Member Accounts.
Note: You must run this script in an Organizations Master Account with all Features Enabled.
Each Member Account must have an OrganizationAccountAccessRole who's name matches the string provided to the variable orgs_access_role_name in the script. The OrganizationAccountAccessRoles must have the proper IAM permissions to perform all Config API calls contained in the script. The credentials used to run the script in the Organizations Master Account must have IAM permissions to List Accounts in Organizations as well as perform the requisite Config Service API calls in the Master Account.
This script requires Python3 installed and the boto3 library.
Also note that this script does not enable Config Service in your AWS Accounts, only create an Aggregator and authorize it. If you are looking for a solution to manage the Config Service and it's Rules across multiple AWS Accounts please check out the links below. [2][3]

AWS Creds Profile Manager - An easier way to manage your AWS CLI/SDK config and credentials files

Source code and download:

https://github.com/walkerk1980/AWSCredsProfileManager

examples:
awsprofilemanager.py -r us-west-2 -a AKID0123456789012 -s 'YourSecretAccessKey/klngs/a49nunf98494n'
awsprofilemanager.py -p saml -r us-east-1 -a AKID0123456789012 -s 'YourSecretAccessKey/klngs/a49nunf98494n' -t 'YourSessionToken/d932u98unf43/a93uh'
For more info on AWS config and credentials files please see the AWS Documentation. [1][2]
[2] AWS Config/Credential File Format - https://docs.aws.amazon.com/cli/latest/topic/config-vars.html


usage: awsprofilemanager.py [-h] [-p [PROFILE]]
                            [-r [{ap-south-1,ap-northeast-2,ap-southeast-1,ap-southeast-2,ap-northeast-1,ca-central-1,eu-central-1,eu-west-1,eu-west-2,eu-west-3,sa-east-1,us-east-1,us-east-2,us-west-1,us-west-2}]]
                            [-a [ACCESS_KEY_ID]] [-s [SECRET_ACCESS_KEY]]
                            [-t [SESSION_TOKEN]] [-o [{json,text,table}]]
                            [-R [ROLE_ARN]] [-S [ROLE_SESSION_NAME]]
                            [-P [SOURCE_PROFILE]]
                            [-c [{Environment,Ec2InstanceMetadata,EcsContainer}]]
                            [-e [EXTERNAL_ID]] [-m [MFA_SERIAL]]
                            [-f [CONFIG_FILE_PATH]] [-d [DURATION_SECONDS]]

optional arguments:
  -h, --help            show this help message and exit
  -p [PROFILE], --profile [PROFILE]
                        The name of the profile to create or overwrite
  -r [{ap-south-1,ap-northeast-2,ap-southeast-1,ap-southeast-2,ap-northeast-1,ca-central-1,eu-central-1,eu-west-1,eu-west-2,eu-west-3,sa-east-1,us-east-1,us-east-2,us-west-1,us-west-2}], --region [{ap-south-1,ap-northeast-2,ap-southeast-1,ap-southeast-2,ap-northeast-1,ca-central-1,eu-central-1,eu-west-1,eu-west-2,eu-west-3,sa-east-1,us-east-1,us-east-2,us-west-1,us-west-2}]
                        the region to set for the profile
  -a [ACCESS_KEY_ID], --access-key-id [ACCESS_KEY_ID]
                        AccessKeyID to set in the profile
  -s [SECRET_ACCESS_KEY], --secret-access-key [SECRET_ACCESS_KEY]
                        The SecretAccessKey to set for the profile
  -t [SESSION_TOKEN], --session-token [SESSION_TOKEN]
                        The SessionToken to set for the profile
  -o [{json,text,table}], --output [{json,text,table}]
                        Default output style
  -R [ROLE_ARN], --role-arn [ROLE_ARN]
                        The ARN of the Role to set for the profile to assume
  -S [ROLE_SESSION_NAME], --role-session-name [ROLE_SESSION_NAME]
                        The Role Session Name to set for the profile to use
  -P [SOURCE_PROFILE], --source-profile [SOURCE_PROFILE]
                        The name of the source profile to set
  -c [{Environment,Ec2InstanceMetadata,EcsContainer}], --credential-source [{Environment,Ec2InstanceMetadata,EcsContainer}]
                        The credential provider to use to get credentials for
                        the initial assume-role call
  -e [EXTERNAL_ID], --external-id [EXTERNAL_ID]
                        A unique identifier that is used by third parties to
                        assume a role
  -m [MFA_SERIAL], --mfa-serial [MFA_SERIAL]
                        The identification number of the MFA device to use
                        when assuming a role
  -f [CONFIG_FILE_PATH], --config-file-path [CONFIG_FILE_PATH]
                        Path to he file to create the profile in, defaults to
                        ~/.aws/config
  -d [DURATION_SECONDS], --duration-seconds [DURATION_SECONDS]
                        The duration, in seconds (900..max_session_duration)
                        of the role session. Default=3600

Thursday, April 25, 2019

THURSDAY, APRIL 25, 2019 CloudHSM client container based on Ubuntu with CloudHSM client, PKCS#11 library and PyKCS11 module installed and ready to use within a Docker/Kubernetes.

Docker Hub: https://hub.docker.com/r/walkerk1980/cloudhsm-pkcs11-python
View the code on GitHub: https://github.com/walkerk1980/cloudhsm-pkcs11-python

Prerequisites:
Container host Instance requires either an EC2 Instance Profile to be attached to the host Instance with IAM permissions that allow the container to pull the CloudHSM Cluster information or you can alternatively pass the container IAM Access Key Credential via Docker Environment Variables. [1][2]
This container requires you to provide the CLUSTERID of an HSM Cluster with at least one running HSM in the same Region/VPC as the host.

The Cluster/HSM requires the proper Security Groups allowing the Instance/Container to communicate with the Cluster.

For more information please see the CloudHSM documentation. [3]
Getting Started:
$ docker volume create --name cloudhsm_data
$ docker run -it -d --rm --name cloudhsm -v cloudhsm_data:/root/data/ walkerk1980/cloudhsm-pkcs11-python /bin/bash
$ docker cp /path/to/customerCA.crt cloudhsm:/root/data/
$ docker stop cloudhsm
$ docker run -it -d -e CLUSTERID=cluster-5la5cwabs7v -v cloudhsm_data:/root/data --name cloudhsm -e REGION=us-west-2 walkerk1980/cloudhsm-pkcs11-python /usr/local/bin/startup.sh
Example commands once the container is running:
ensure that client is connected: 
$ docker logs cloudhsm
connect to bash on container: 
$ docker exec -it cloudhsm
Within bash - create CA: 
$ createCA.sh
Within bash - CloudHSM Managment Utilitiy: 
$ /opt/cloudhsm/bin/cloudhsm_mgmt_util /opt/cloudhsm/etc/cloudhsm_mgmt_util.cfg

ENVIRONMENT VARIABLES:
CLUSTERID is for the Cluster Id of your initialized CloudHSM Cluster containing at least one running HSM.
REGION is for the AWS Region that your CloudHSM Cluster is located in.
CASUBJECT (Optional) is for the subject of the local CA to be created.
CAKEYPASS (Optional) is for the local CA private key password.
AWS_ACCESS_KEY_ID (Optional) is for pulling requried cluster information if Instance Profile is not used.
AWS_SECRET_ACCESS_KEY (Optional) is for pulling requried cluster information if Instance Profile is not used.
AWS_SESSION_TOKEN (Optional) is for pulling requried cluster information if Instance Profile is not used.

Internal Container Commands:
createCA.sh - Set up the local CA using the information provided in CASUBJECT and CAKEYPASS. This will create an openssl CA and move it to the data volume
cainfo.sh - Get info about the customerCA.crt in place within the container

Friday, September 8, 2017

Automate OpenSSL to pull a certificate thumbprint for an OIDC IDP

How to automatically pull the certificate thumbprint for an Open Identity Connect Providers certificate instead of the manual process described at http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html

You could use this process along with 'aws iam update-open-id-connect-provider-thumbprint' to automate the process of regularly pulling the certificate from your IDP and updating it's thumbprint in IAM.

code can be found at: https://github.com/walkerk1980/AWSScripts/blob/master/oidcThumbprint.pl

#!/usr/bin/perl

# The purpose of this script is to automate the process described in the link below
# Use this script at your own risk
# Obtaining the Thumbprint for an OpenID Connect Identity Provider
# http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html

#requires bash
#requires jq package
#requires perl
#requires openssl

#set the oidc idp URL
my $idpURL='https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/v2.0/.well-known/openid-configuration';

my $cmd='curl -s ' . $idpURL . ' |jq -r \'.jwks_uri\'';

#run output of curl through jq
my $jwksURI=`$cmd`;

#cut off prepended https://
my $fullURL=substr($jwksURI, 8);

#cut off host of URL
my $hostURL=substr($fullURL, 0, index($fullURL, '/'));

$cmd='openssl s_client -showcerts -connect ' . $hostURL . ':443 </dev/null 2>/dev/null';

#use ssl_connect to get certificate chain
my $sslclientoutput=`$cmd`;

#cut junk off beginning of last cert
my $lastcertsub1=substr(substr($sslclientoutput, rindex($sslclientoutput, 'BEGIN')-5), 'END');
#cut junk off end of cert
my $lastcert=substr($lastcertsub1, 0, index($lastcertsub1, 'END')+20);

#create pem file
$cmd='echo "' . $lastcert . '" >oidcert.pem';
system($cmd);

$cmd='openssl x509 -fingerprint -noout -in oidcert.pem';
my $opensslfinger=`$cmd`;

#cut off junk at beginning
my $fingerprint=substr($opensslfinger, index($opensslfinger, '=')+1);

#get rid of colons
$fingerprint =~  s/://g;

print $fingerprint


Thursday, October 13, 2016

Check for a hotfix on a remote Windows Server with WMI

 $KB = Read-Host -Prompt "Enter KB number: "  
 $computername = Read-Host -Prompt "Enter FQDN of Computer or IP"  
 $query = "select HotFixID from Win32_QuickFixEngineering"  
 $HotFixes = Get-WmiObject -Query $query -ComputerName $computername  
 $found = $false  
 foreach ($HotFix in $HotFixes)  
 {  
   #Write-Host $HotFix.HotFixID  
   if ($HotFix.HotFixID -eq $KB)  
   {  
     Write-Host "HotFix $KB installed"  
     $found = $true  
   }  
 }  
 if ($found -eq $false)  
 {  
   Write-Host "HotFix not found"  
 }  
 Clear-Variable $HotFixes  

Tuesday, May 10, 2016

Puppet module to install PowerBroker open and join machines to domain

init.pp
class pbis (
  $domain = $pbis::params::domain,
  $ldapbindaccount = $pbis::params::ldapbindaccount,
  $ldapbindpassword = $pbis::params::ldapbindpassword,
  $sudogroup = $pbis::params::sudogroup,
) inherits pbis::params {
}

params.pp
class pbis::params {
  $domain = 'example.com'
  $ldapbindaccount = 'user'
  $ldapbindpassword = 'password'
  $sudogroup = 'domain^admins'
}

install.pp
class pbis::install inherits pbis {
  include apt

  apt::source { 'powerbroker':
    comment  => 'Powerbroker Identity Services',
    location => 'http://repo.pbis.beyondtrust.com/apt',
    release  => 'pbiso',
    repos    => 'main',
    pin      => '500',
    key      => {
      'source'     => 'http://repo.pbis.beyondtrust.com/yum/RPM-GPG-KEY-pbis',
      'id'         => 'BE7FF72A6B7C8A9FAE061F4F2E52CD89C9CEECEF',
    },
    include  => {     
      'deb' => true,
    },
  }

  exec { 'pbis-apt-get-update':
    command => '/usr/bin/apt-get update',
    refreshonly => true,
  }

  package { 'pbis-open' :
    ensure => installed,
    provider => apt,
#    source => '/root/pbis-open-8.3.0.3287.linux.x86_64.deb',
  }

  $joindomain = "#!/bin/bash
    domainjoin-cli join $domain \$1 \$2       
    cd /opt/pbis/bin/  
    ./config UserDomainPrefix $domain
    ./config AssumeDefaultDomain true
    ./config LoginShellTemplate /bin/bash
    ./config HomeDirTemplate %H/%U
    ./config RequireMembershipOf '$domain\domain^users'
    "

  file { '/usr/local/bin/join-domain.sh' :
    ensure => present,   
    owner => root,
    group => root,
    mode => '0544',
    content => "$joindomain"
  }
}

join.pp
class pbis::join inherits pbis {

$sudofile="#
# This file MUST be edited with the visudo command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"
# Host alias specification
# User alias specification
# Cmnd alias specification
# User privilege specification
root    ALL=(ALL:ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
#Domain Admins
%$domain\\\\$sudogroup        ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on #include directives:
#includedir /etc/sudoers.d
"
  file { '/etc/sudoers' :
    ensure => present,
    owner => root,
    group => root,
    mode => '0440',
    content => "$sudofile"
  }

  exec { 'join':
    command => "/usr/local/bin/join-domain.sh $ldapbindaccount $ldapbindpassword",
    require => Class['pbis::install'],
    unless => "/bin/echo $(/usr/bin/domainjoin-cli query)|/bin/grep $domain",
  }
}

Simple puppet class for a squid server with allow all in conf


install.pp

class squid::install inherits squid {
  include apt

  exec { 'squid-update-apt':
    command => '/usr/bin/apt-get update',
    refreshonly => true,
  }

  package { 'squid3' :
    require => Class['squid::setup'],  
    ensure => installed,
    provider => apt,
  }


}

setup.pp

class squid::setup inherits squid {

  $squidconf="acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT
http_access allow all
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localhost
http_access deny all
http_port 3128
coredump_dir /var/spool/squid3
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern (Release|Packages(.gz)*)$      0       20%     2880
refresh_pattern .               0       20%     4320
"

  file { '/etc/squid3/squid.conf' :
    notify => Service['squid3'],
    ensure => present,
    owner => root,
    group => root,
    mode => '0644',
    content => $squidconf
  }
}

init.pp
class squid (
  $example = $squid::params::example,
) inherits squid::params {
}

params.pp
class squid::params {
  $example = 'example1'
}

Friday, March 25, 2016

Way more fun AD C# functions...

This goes well with my last post!
     public void UnlockUser(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             else  
             {  
               MessageBox.Show(usr.DisplayName + "'s account not locked, " + "last logon at " + usr.LastLogon.ToString() + ", " + "user has " + usr.BadLogonCount.ToString() + " bad password attempts.");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void ResetUsersPassword(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string resetPasswordString = "Are you sure you want to reset " + usr.DisplayName + "'s password?";  
             yesNoDialog = MessageBox.Show(resetPasswordString, "Password Reset", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               usr.SetPassword("Password1");  
               usr.ExpirePasswordNow();  
               MessageBox.Show(usr.DisplayName + "'s password has been reset.");  
             }  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void PsLoggedOn(string psLoggedOnArgs, string pcname)  
     {  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         DialogResult yesNoDialog;  
         yesNoDialog = MessageBox.Show("Would you like to run psLoggedIn also?", "psLoggedOn?", MessageBoxButtons.YesNo);  
         if (yesNoDialog == DialogResult.Yes)  
         {  
           try  
           {  
             System.Diagnostics.Process proc = new System.Diagnostics.Process();  
             proc.EnableRaisingEvents = false;  
             proc.StartInfo.FileName = "psLoggedOn";  
             proc.StartInfo.UseShellExecute = false;  
             if (PcNameIsNotNullOrVoid(pcname))  
             {  
               proc.StartInfo.Arguments = " " + backslashes + pcname + " " + psLoggedOnArgs;  
             }  
             proc.StartInfo.RedirectStandardOutput = true;  
             proc.Start();  
             //string tasklist = proc.StandardOutput.ReadToEnd();  
             MessageBox.Show(proc.StandardOutput.ReadToEnd());  
             //proc.WaitForExit();  
           }  
           catch (Exception tasklistException)  
           {  
             MessageBox.Show(tasklistException.Message);  
           }  
         }  
       }  
     }  
     public List<string> GetGroups(string user, string fQDomainName, string ou)  
     {  
       List<string> groupList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             var groups = usr.GetGroups();  
             foreach (Object gr in groups)  
             {  
               groupList.Add(gr.ToString());  
               //MessageBox.Show(gr.ToString());  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
           return groupList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           return groupList;  
         }  
       }  
       return groupList;  
     }  
     public void DisableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
                 string removeGroupsString = "Would you like to remove " + usr.DisplayName + " from all AD groups and move to Disabled Users OU?";  
                 yesNoDialog = MessageBox.Show(removeGroupsString, "Remove AD Groups?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   RemoveUserFromAllGroups(user, fQDomainName, ou);  
                   MoveToDisabledUsersOU(usr.DistinguishedName, disabledUsersOU);  
                   MessageBox.Show(usr.DisplayName + " has been removed from all AD groups and moved to Disabled Users.");  
                 }  
                 string deleteTSProfilesString = "Would you like to delete " + usr.DisplayName + "'s profiles from all the Terminal Servers?";  
                 yesNoDialog = MessageBox.Show(deleteTSProfilesString, "Delete TS Profiles?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   DiskTools dt = new DiskTools();  
                   dt.DeleteTSProfiles(usr.SamAccountName.ToLower());  
                   MessageBox.Show(usr.DisplayName + "'s profiles are being deleted from all terminal servers.");  
                 }  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
       else  
       {  
         MessageBox.Show("User not found");  
       }  
     }  
     public void DisableAccountTemp(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to temporarily disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Temporarily Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void EnableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string enableAccountString = "Are you sure you want to enable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(enableAccountString + userInfoString, "Enable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == false)  
               {  
                 usr.Enabled = true;  
                 //usr.SetPassword("Password1");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "enabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been enabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already enabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void AddUserToGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Add(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Remove(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromAllGroups(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           List<string> groupList = GetGroups(user, fQDomainName, ou);  
           foreach (object group in groupList)  
           {  
             if (!string.Equals(group.ToString(), "Domain Users"))  
             {  
               RemoveUserFromGroup(user, fQDomainName, ou, group.ToString());  
             }  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void MoveToDisabledUsersOU(string userDN, string newOU)  
     {  
       //Move an object from one ou to another  
       DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + userDN);  
       DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newOU);  
       string newName = eLocation.Name;  
       eLocation.MoveTo(nLocation, newName);  
       nLocation.Close();  
       eLocation.Close();  
     }  
     public string RandomPassword(int passwordLength)  
     {  
       string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";  
       char[] chars = new char[passwordLength];  
       Random rd = new Random();  
       for (int i = 0; i < passwordLength; i++)  
       {  
         chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];  
       }  
       return new string(chars);  
     }  
     public void PopulateADLocations(string fQDomainName, string ou)  
     {  
       foreach (string location in Properties.Settings.Default.ADLocations)  
       {  
         //populations AD PhysicalDeliveryOfficeName field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", location);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Office", location);  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + location + " complete.");  
         myRunSpace.Dispose();  
       }  
     }  
     public void PopulateADTitles(string fQDomainName, string ou)  
     {  
       foreach (string title in Properties.Settings.Default.ADTitles)  
       {  
         //populations AD Title field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", title);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Title", title.TrimEnd('s'));  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + title + " complete.");  
         myRunSpace.Dispose();  
       }  
    }  

Get Some AD info in C#

     private void getUsersADInfoToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       UserTools ut = new UserTools();  
       var combinedList = new List<string>();  
       combinedList.AddRange(ut.GetADUserInfo(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       combinedList.Add("");  
       combinedList.Add("GROUP MEMBERSHIPS: ");  
       combinedList.AddRange(ut.GetGroups(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       //ListBoxForm.ShowList(combinedList, "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       TextBoxForm.ShowText(string.Join<string>(Environment.NewLine, combinedList), "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
     }  
     public List<string> GetADUserInfo(string user, string fQDomainName, string ou)  
     {  
       List<string> resultList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             resultList.Add("NAME:\t\t" + usr.DisplayName);  
             resultList.Add("TITLE:\t\t" + usr.title);  
             resultList.Add("DEPARTMENT:\t" + usr.department);  
             resultList.Add("COMPANY:\t" + usr.company);  
             resultList.Add("OFFICE:\t\t" + usr.office);  
             resultList.Add("EMAIL:\t\t" + usr.EmailAddress);  
             resultList.Add("LOGIN:\t\t" + usr.SamAccountName);  
             resultList.Add("PROFILE:\t" + usr.HomeDirectory);  
             if(!string.IsNullOrEmpty(usr.Description))  
             {  
               resultList.Add("DESCRIPTION:\t" + usr.Description);  
             }  
             usr.Dispose();  
           }  
           else resultList.Add("");  
           ctx.Dispose();  
           return resultList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           resultList.Add("");  
           return resultList;  
         }  
       }  
       else resultList.Add("");  
       return resultList;  
     }  
     public string GetSamAccountName(string user, string fQDomainName, string ou)  
     {  
       string samAccountName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             samAccountName = usr.SamAccountName.ToString();  
             usr.Dispose();  
           }  
           else samAccountName = "";  
           ctx.Dispose();  
           return samAccountName;  
         }  
         catch (Exception getSamAccountNameException)  
         {  
           MessageBox.Show(getSamAccountNameException.Message);  
           samAccountName = "";  
           return samAccountName;  
         }  
       }  
       else samAccountName = "";  
       return samAccountName;  
     }  
     public string GetFullName(string user, string fQDomainName, string ou)  
     {  
       string fullName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             fullName = usr.Name.ToString();  
             usr.Dispose();  
           }  
           else fullName = "";  
           ctx.Dispose();  
           return fullName;  
         }  
         catch (Exception getFullNameException)  
         {  
           MessageBox.Show(getFullNameException.Message);  
           fullName = "";  
           return fullName;  
         }  
       }  
       else fullName = "";  
       return fullName;  
     }  
     public string GetEmailAddress(string user, string fQDomainName, string ou)  
     {  
       string emailAddress;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             emailAddress = usr.EmailAddress.ToString();  
             usr.Dispose();  
           }  
           else emailAddress = "";  
           ctx.Dispose();  
           return emailAddress;  
         }  
         catch (Exception getEmailException)  
         {  
           MessageBox.Show(getEmailException.Message);  
           emailAddress = "";  
           return emailAddress;  
         }  
       }  
       else emailAddress = "";  
       return emailAddress;  
     }  
     public string GetManager(string user, string fQDomainName, string ou)  
     {  
       string managerName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             managerName = GetFullName(usr.manager, fullyQualifiedDomainName, organizationalUnit);  
             usr.Dispose();  
           }  
           else managerName = "";  
           ctx.Dispose();  
           return managerName;  
         }  
         catch (Exception getManager)  
         {  
           MessageBox.Show(getManager.Message);  
           managerName = "";  
           return managerName;  
         }  
       }  
       else managerName = "";  
       return managerName;  
     }  
     public string GetCompany(string user, string fQDomainName, string ou)  
     {  
       string company;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             company = usr.company.ToString();  
             usr.Dispose();  
           }  
           else company = "";  
           ctx.Dispose();  
           return company;  
         }  
         catch  
         {  
           MessageBox.Show("Warning: Company not set!");  
           company = "";  
           return company;  
         }  
       }  
       else company = "";  
       return company;  
     }  

Wednesday, March 23, 2016

Restart a remote computer's print spooler and delete it's print jobs via C#

Custom functions not included PcNameIsNotNullOrVoid(pcname), CleanPCName(pcname), variables such as cshare, etc. Utilizes windows built in psservice.exe.
     public void RestartTheSpooler(string pcname)  
     {  
       try  
       {  
         StopTheSpooler(pcname);  
         Thread.Sleep(1500);  
         //Thread stopSpoolThread = new Thread(new ThreadStart(stopTheSpooler));  
         //stopSpoolThread.Start();  
         DeletePrintJobs(pcname);  
         StartTheSpooler(pcname);  
       }  
       catch (Exception spoolerException)  
       {  
         MessageBox.Show(spoolerException.Message);  
       }  
     }  
     public void StopTheSpooler(string pcname)  
     {  
       pcname = CleanPCName(pcname);  
       //stop spooler  
       System.Diagnostics.Process stopspooler = new System.Diagnostics.Process();  
       stopspooler.EnableRaisingEvents = false;  
       stopspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         stopspooler.StartInfo.Arguments = backslashes + pcname + " stop spooler";  
         stopspooler.Start();  
         stopspooler.WaitForExit();  
       }  
     }  
     public void DeletePrintJobs(string pcname)  
     {  
       //delete print jobs  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         if (Directory.Exists(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers\"))  
         {  
           Directory.Delete(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers", true);  
         }  
         Directory.CreateDirectory(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\PRINTERS");  
       }  
     }  
     public void StartTheSpooler(string pcname)  
     {  
       //start spooler  
       System.Diagnostics.Process startspooler = new System.Diagnostics.Process();  
       startspooler.EnableRaisingEvents = false;  
       startspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         startspooler.StartInfo.Arguments = backslashes + pcname + " start spooler";  
         startspooler.Start();  
       }  
     }  

Wednesday, March 9, 2016

Puppet install.pp for PBIS-Open

An install.pp in the works for PowerBroker that uses the official ppa. Haven't gotten around to finishing my join.pp yet, will post when I do.
 class optivlabsdomain::install inherits optivlabsdomain {  
  include apt  
  apt::source { 'powerbroker':  
   comment => 'Powerbroker Identity Services',  
   location => 'http://repo.pbis.beyondtrust.com/apt',  
   release => 'pbiso',  
   repos  => 'main',  
   pin   => '500',  
   key   => {  
    'source'   => 'http://repo.pbis.beyondtrust.com/yum/RPM-GPG-KEY-pbis',  
    'id'     => 'BE7FF72A6B7C8A9FAE061F4F2E52CD89C9CEECEF',  
   },  
   include => {  
    'deb' => true,  
   },  
  }  
  exec { 'apt-get update':  
   command => '/usr/bin/apt-get update',  
   refreshonly => true,  
 #  unless => "/usr/local/bin/pbis-installed.sh",    
  }  
  package { 'pbis-open' :  
   ensure => installed,  
   provider => apt,  
  }  
 # file { '/root/pbis-open-8.3.0.3287.linux.x86_64.deb.sh' :  
 #  ensure => present,  
 #  owner => root,  
 #  group => root,  
 #  mode => '0544',  
 #  source => 'puppet:///files/pbis-open-8.3.0.3287.linux.x86_64.deb.sh'  
 # }  
 # file { '/usr/local/bin/pbis-installed.sh' :  
 #  ensure => present,  
 #  content => "$(dpkg-query -W -f='\${status}' pbis-open 2>/dev/null | grep -c 'ok installed')'",  
 #  mode => '0544',  
 #  owner => root,  
 #  group => root,  
 # }  
 # exec { 'install.sh':  
 #  command => '/root/pbis-open-8.3.0.3287.linux.x86_64.deb.sh install',  
 #  refreshonly => true,  
 #  unless => "/usr/local/bin/pbis-installed.sh",    
 # }  
 }