Tag Archives: Powershell

Reset passwords for Active Directory Users

Reset and manage your Active Directory users' Passwords

Active Directory is one of the most esential and important tool in any company whether small or big. In most cases big companies have uncountable amount of tools to maintain and protect users and their credentials however almost most of those companies are not prepared to the time when their systems have been compromised or to say the least their servers have been hacked or encrypted by ransomware which is something we hear very often nowadays like the case with Louisiana Hospital that was attacked by Ransomware exposing the data of 270000 patients. 

Realistic scenario

What if your users passwords were compromised and you’re not sure who is still safe or not but you need to act as fast as possible? 

To act fast, I created a script that would generate a complex 32 Char long password with 4 different Non Alphanumeric Characters using the System.Web.Security.Membership  class. here’s an example of this password:

81Q:#_#E-QVZ-(1m&VS1LKpbzwR+8Em%

The script details

The script will first check if you have the Powershell Get and ImportExcel Module installed, if not it’ll ask you to install it or not. 

You will need to amend few things

1- The path to reflect where you want to save the Logs, CSV and Excel sheet. as of now it’s in c:\SyncReports. 

2- Importing users, In the script I am grabbing users directly from a specific OU in AD. so you’ll need to decide how you want to do it. I have added another line in case you’re planning to 

3- The password reset command is setup with -whatif parameter for you to test this before you run it. so just remember to remove it when you’re done with the changing and testing.

I have added mailbody and send-message command to send the excel as an attachment along with the excel password protection. 

Running the script will result in the following

Once you get the Excel sheet and try to open it, you will realize that it’s password protected. The password should be in the email body that’s sent in the script.

Excel sheet result will be looking as follows:

The script
The script 90%
#This script will generate randdom complex passwords for all AD users

#Using Time class and start reporting
$TimeStamp = [datetime]::Now.ToString(“MM-dd-yyyy-HH-mm”)
Start-Transcript -Path C:\SyncReports\Logs\Logs_$TimeStamp.txt -IncludeInvocationHeader

#Generate report
$Report = [System.Collections.Generic.List[Object]]::new()

#Check if Excel Module is installed, if not it’ll ask to install it

##Check Protocol and Setting Secure Connectivity

[Net.ServicePointManager]::SecurityProtocol
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls, [System.Net.SecurityProtocolType]::Tls11,[System.Net.SecurityProtocolType]::Tls12

#Install PowershellGet and ImportExcel Modules
if (Get-Module -ListAvailable -Name PowershellGet) {
    Write-Host “PowershellGet exists”
} else {Install-Module PowershellGet -Force}
if (Get-Module -ListAvailable -Name ImportExcel) {
    Write-Host “ImportExcel exists”
}
else {
    Write-host “Module does not exist, Would you like to install it?”
    $options = [System.Management.Automation.Host.ChoiceDescription[]] @(‘&Yes’, ‘&No’)
    if(0 -eq $host.UI.PromptForChoice(‘Install?’ , ‘Would you like to install ImportExcel’ , $Options,0)){
        Write-Host “Installing Excel Module”… -fore green
        Install-Module -Name ImportExcel
        return
    }
}

# Import System.Web assembly
Add-Type -AssemblyName System.Web

#Defining where to get users from:
$Users = Get-ADUser -SearchBase “OU=Moh10ly_Users,DC=moh10ly,DC=local” -Filter * -Properties *
#$Users = Import-Csv “C:\SyncReports\Users.csv”
foreach ($User in $Users){
       
        $UID = $User.UserPrincipalName
        $ObjectProp = Get-ADUser -Filter {(Mail -like $UID) -or (UserPrincipalName -like $UID)} -Properties *

        #Generate New Password
        $NewPassword=[System.Web.Security.Membership]::GeneratePassword(32,4)
        $Password= ConvertTo-SecureString $newPassword -AsPlainText -Force
        $TEXTO = “$newPassword”
        $ENCODED1 = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($TEXTO))
       
        $Name = $ObjectProp.Name
        $SAM = $ObjectProp.SamAccountName

        if($SAM){
 
                   
                         $ReportLine = [PSCustomObject][Ordered]@{
                            DateandTime                 = $TimeStamp
                            UPN                         = $ObjectProp.UserPrincipalName
                            DisplayName                 = $ObjectProp.Displayname
                            Email                       = $ObjectProp.Mail
                            Encoded                     = $ENCODED1
                            Password                    = $newPassword
                            Error                       = $ObjectProp.Exception.Message
                            }
                           
                            $Report.Add($ReportLine)
           
            #Wait for Email to send
            #Start-Sleep -Seconds 15

            #Resetting user’s password
            Set-ADAccountPassword -Identity $User.SamAccountName -NewPassword $Password -WhatIf

        }
    else {$Error = Write-Host -f Red “$($User) Couldn’t be found”    
    #send-mailmessage -from “admin@skybirdtravel.com” -to “admin@skybirdtravel.com” -subject “Password reset didn’t work for $($User.UserprincipalName) on $TimeStamp” -body “$Error” -Priority High -smtpServer mailcleaner.cloudapphost.net}
    }
}
Stop-Transcript
Write-Host (“{0} Users processed” -f $Users.count)
#$Report | Out-GridView
$ExcelPassword =[System.Web.Security.Membership]::GeneratePassword(32,4)
$Report | Select-Object UPN,Displayname,Email,Encoded,Password | Export-Csv -NoTypeInformation “C:\SyncReports\UserReset_$TimeStamp.csv”
$Report | Export-Excel “C:\SyncReports\UserReset_$TimeStamp.xlsx” -WorksheetName Users -TableName Users -AutoSize -Password “$ExcelPassword”
$Exported = “C:\SyncReports\UserReset_$TimeStamp.xlsx”
$MailBody = “
            <html><body>
            <font color=’006400′> Dear Team, Please find attached the list of users and their passwords encoded … `
            The file is protected with password // $ExelPassword // If any issue you can send an email to support@domain.com .</font>
            <body><html>
            “
$CC = @(‘info@moh10ly.com’)

#Get-ChildItem $Exported | send-mailmessage -from “admin@domain.com” -to “report@domain.com” -Cc $CC -subject ” User Passwords List for the date $date” -body “$MailBody” -Priority High -smtpServer relay.domain.com -BodyAsHtml

Finally:

I have added this script to github, so feel free to comment or add your contribution if needed.

https://github.com/moh30ly/powershell/blob/main/ADPasswordChange

Checking and Providing Full and SendAs delegate access on O365 Exchange Online

Delegate Permissions

This is a code that I have wrote recently to check if an account have Full and SendAs access on target mailboxes in CSV and give the option to choose whether to provide this access or not.

Checking First:

You’ll need to provide two things to get this code working, First the Source account that will need access to the mailboxes. in this case referred to as “ServiceAccount”.

CSV List of Mailbxoes:

You’ll need to provide list of Mailboxes of the users you’d like to provide access to, the List must be user’s Identity either UPN or SMTP would be fine.

The Service account’s Identity must be the UPN attribute.

If you would like to improve this code please do comment or get in touch directly

Thanks

#Connect to Exchange
#Connect & Login to ExchangeOnline (MFA)

try
{
    Get-Clutter -Identity user@domain.com -ErrorAction Stop > $null
}
catch 
{
Connect-ExchangeOnline
}

    $Users = import-csv 'C:\CSV\MailboxListIsHere.csv'
    $ServiceAccount = 'Your Account that will access other Mailboxes' #// Please change the SVC account before running the code
    

        foreach ($User in $users)
        {
            $Mailbox = $User.Identity
            
            #Checking Full Access
            $Full = Get-MailboxPermission -Identity $Mailbox -User $ServiceAccount
            If ($Full.AccessRights -eq "FullAccess")
            {
                Write-Host -f Green $($ServiceAccount) "Already has Full access to $Mailbox."}
            
                    Else
                    {
                        $Answer1 = Read-Host "Do you want to assign $($ServiceAccount) Full access to $Mailbox (Yes or No)"
                        If ($Answer1 -eq "Yes")
                            {
                                Try{
                                    Add-MailboxPermission -Identity $Mailbox -User $ServiceAccount -AccessRights FullAccess
                                    Write-Host -f DarkGreen $($ServiceAccount) "Send-as access has been added to $Mailbox"
                                    }
                           
                            Catch{ ($Full.AccessRights -eq "FullAccess")}
                            
                        }
                        
                    }
                
                $SendAs = Get-RecipientPermission -Identity $Mailbox -Trustee $ServiceAccount -AccessRights SendAs
                if($SendAs.AccessRights -eq "SendAs") {
                    Write-Host -f Green $($ServiceAccount) "Already has SendAs access to $Mailbox."
                    }
                    Else
                    {
                        $Answer2 = Read-Host "Do you want to assign $($ServiceAccount) Send-as access to $Mailbox (Yes or No)"
                        If ($Answer2 -eq "Yes")
                            {
                                Try{
                                    Add-RecipientPermission -Identity $Mailbox -AccessRights SendAs -Trustee $ServiceAccount
                                    Write-Host -f Green $($ServiceAccount) "has Send-as access on $Mailbox"
                                }
                            Catch{($SendAs.AccessRights -eq "Sendas")}}
                            else{Exit}
                        }
                    }
        }
            
        

550 relay not permitted distribution group contact

550 relay not permitted distribution group contact

Symptoms

When trying to add an external contact inside a Distribution group. A failure delivery mail with the following NDR is returned.

Delivery has failed to these recipients or groups:

Externalcontact@domain.com

Your message couldn’t be delivered and there was no valid enhanced status code being issued by the remote mail system to determine the exact cause, status: ‘550 relay not permitted’.

The following organization rejected your message: mxserver

Header

Diagnostic information for administrators:

Generating server: server
Externalcontact@domain.com

Remote Server returned '550 relay not permitted'

Original message headers:

Resent-From: <inboundemail@Exchangedomain.com>
Received: from 
with Microsoft SMTP Server (version=TLS1_2,
 cipher=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P521) id 15.1.2375.17; Wed, 15
 Dec 2021 11:53:30 -0500
Received: from mail-ot1-f41.google.com (209.85.210.41) by
 with Microsoft SMTP Server (version=TLS1_2,
 cipher=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA_P384) id 15.1.2375.17 via Frontend
 Transport; Wed, 15 Dec 2021 11:53:30 -0500
Received: by mail-ot1-f41.google.com with SMTP id a23-20020a9d4717000000b0056c15d6d0caso25610296otf.12
        for <inboundemail@Exchangedomain.com>; Wed, 15 Dec 2021 08:53:01 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=gmail.com; s=20210112;
        h=mime-version:references:in-reply-to:from:date:message-id:subject:to;
        bh=rR2IMeF7H4JDA9rxaP9qe9SS4+k1fEFk6/Y7HUCR5us=;
        b=NV4VaI1l4JibchEYURu8Z0pAkxU2Km1s5xNxC3pE+vHL/7vd77ut2ri0zUvBqMRcLr
         kOSnRYnDeMnc7EAbsOJRP2oSx6afnHB1yN8WjMijDE/Va/0jOp7Ni4K0PTXIyz2X0W5i
         VPQuoTgOsyKkjN+HZqVpXgxHy8RyRNkiTnUsutwRIZZWevIoHC/p0cwad8yN6tIdCVif
         IMkACRMkA0HeAzBR/v0ctAChdUpkbcBXA+85hbuO2O8CQdXBCBCf4EzpjqiI97QK24yf
         oedS61hmS2qb2zFQ6f8qxmYBgxdK4lQWdI9TdurXmpnQHBKZFIqW56US0cMQ3jCpSF9q
         Se2A==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20210112;
        h=x-gm-message-state:mime-version:references:in-reply-to:from:date
         :message-id:subject:to;
        bh=rR2IMeF7H4JDA9rxaP9qe9SS4+k1fEFk6/Y7HUCR5us=;
        b=qVj/PXzNyVqwff+McPc2WmcrhKnU1KzHFugZOqxTRB+v+IKASjxOXzq4oernUflv1P
         ApDShejS2jAO6czxgamOrV4i4E7MUlqM1ZOAORM1+ZZiicTPhLk4ybx88t6Ex6xWG8x1
         CayHD9LjorI/UGhs60fFXpfxREnRvz1mMXk4RQlUVGn7oQvlJZaApknskvs/KDaxB3K4
         l1HvunANu25x9/zmf6OuJEkNuhUQWPnh5TESf52pLknaUmeHBA9Ff4LhEFLoyuj2KwxX
         jDfyvQ3RRs8kN3S+IQntHrukyU6cIy4xskUiSzOUa4wb/b6SfSu7sVb5wy/3MzUcPfwQ
         NJuA==
X-Gm-Message-State: AOAM532yV7/oLUbulh/fnSKX/dvcwEJRrBUakKGRB2AAjJBFmHgQ1juk
	htSdNKTpkhrpu4K0SDKv8LbcseSolYSLvjbVKAFNgKmI1m/3Fg==
X-Google-Smtp-Source: ABdhPJyCyLPmOHEOsFfrUD36h6e5hI9mquwq0Sr3Q+d/MecZbT33ghjh5xXztarpHRBZm944nU8Zrrg/gk50FxN5cxk=
X-Received: by 2002:a9d:7b51:: with SMTP id f17mr9431931oto.88.1639587180247;
 Wed, 15 Dec 2021 08:53:00 -0800 (PST)
MIME-Version: 1.0
References: <cad49hozzrxa94krz4t+3pdqre=npiq+vv8svw3hbcnyzbca_dg@mail.gmail.com>
In-Reply-To: <cad49hozzrxa94krz4t+3pdqre=npiq+vv8svw3hbcnyzbca_dg@mail.gmail.com>
From: External Sender <Sender@gmail.com>
Date: Wed, 15 Dec 2021 22:22:47 +0530
Message-ID: <cad49hoym7ryqqfrzm++=xse4yh-g6pzy10xfo_bqnpyffhc=9g@mail.gmail.com>
Subject: Fwd: test email to Exchange DG
To: <inboundemail@Exchangedomain.com>
Content-Type: multipart/alternative; boundary="00000000000074fd9b05d33223fa"
Return-Path: Sender@gmail.com
X-Auto-Response-Suppress: DR, OOF, AutoReply

Cause:

By default, the ReportToManagerEnabled parameter is set to False and the ReportToOriginatorEnabled parameter is set to True when a distribution group is created in Exchange Online. When the parameters are both set to False, the Return-Path field in the header of the message is <> (blank). This means that the remote messaging system will not send delivery reports to the user who sent the message to the distribution group.

Additionally, if spam filtering is enabled on the remote messaging system, the message is dropped, and delivery reports are suppressed. This occurs because some anti-spam devices might flag messages whose Return-Path field is blank and not let the messages be delivered.

Resolution:

Set-DistributionGroup -ReportToManagerEnabled $true -ReportToOriginatorEnabled $false -Identity distributiongroup@domain.com

REF:

https://docs.microsoft.com/en-US/exchange/troubleshoot/email-delivery/external-recipients-not-receiving-distribution-group-emails

Testing Office 365 SMTP relay

In order to test Office 365 SMTP relay you will have to create a user with an Exchange online license. After the email is activated for this user you can test this user for relay with the following powershell.

First connect to Microsoft Online service with this user that you’ll be using for relaying.

$msolcred = Get-Credential

Next edit the following powershell with the user’s e-mail and the recipient’s too

Send-MailMessage -From Office365User@Domain.com -To info@moh10ly.com -Subject “Test Email” -Body “Test SMTP Relay Service” -SmtpServer smtp.office365.com -Credential $msolcred -UseSsl -Port 587

clip_image001
clip_image002

https://technet.microsoft.com/en-us/library/dn554323(v=exchg.150).aspx

This test is known as Client SMTP submission you can also use a different method for multiple devices where you can configure them all to point to a single server (IIS) in a method known as IIS for relay with Office 365 however, all the methods what involve office 365 (Only) for relay will require a user with Exchange online license assigned to it.

https://technet.microsoft.com/en-us/library/dn592151%28v=exchg.150%29.aspx

Note:

The use of this command is not recommended for security reasons in particular for not supporting the modern protocols. use it on your own risk and make sure the user assigned to this service has no privilege’s or not any Office 365 feature admin or power user.

Upgrading Exchange Online PowerShell to V2 Module

Managing Exchange Online

If you have Exchange Online and your users are MFA enabled then you most likely will be using Exchange Online’ s ECP (Exchange Control Panel or Admin Center) to connect to Exchange Online PowerShell through the Hybrid Windows since this is the only supported way with MFA.

image

Clicking on Configure would install the PowerShell Module of Exchange Online which looks like the below screenshot.

image

New PowerShell with MFA support

If you have launched Exchange Online PowerShell today then you most likely have noticed there’s a red line stating the possibility to try the new (Preview Version) of Exchange PowerShell V2 .

Microsoft has recently released a new version of Exchange Online PowerShell Module which supports MFA and can be run directly from your computer without the need to login to Exchange Online Admin Center and download any files from there.  Check details in this link

As stated in the article, the Module is just in preview so it has some known and maybe unknown bugs as well.

How to Install it?

The installation process is pretty straightforward, Launch Windows PowerShel as an Administrator (It’s required for the installation).

Run these 4 cmdlets

Set-ExecutionPolicy RemoteSigned
Install-Module PowershellGet –Force
Update-Module PowershellGet
Install-Module -Name ExchangeOnlineManagement

image

You might get a warning that the Module you’re about to install is from an Untrusted Repository, Accept it by typing Y and hit enter

Type the following cmdlet to ensure that Exchange Online Management module is installed

Import-Module ExchangeOnlineManagement; Get-Module ExchangeOnlineManagement

image

Connecting to Exchange Online

To connect to Exchange Online, Run the following cmdlet along with the new parameter –EnableErrorReporting which gives the ability to record all the cmdlets that you have run along with errors generated as well.

Connect-ExchangeOnline -EnableErrorReporting -LogDirectoryPath e:\ExchOnlineLogs.txt -LogLevel All

image

image

After connecting, I am going to try and run two commands the Old Cmdlets and New Cmdlet and see the difference between them:

Get-CASMailbox -ResultSize 10
Get-EXOCasMailbox -ResultSize 10

image

The new Cmdlet has much more details, although it says that it runs faster but it took few seconds more than the old one to run (Probably first time).

image

After you run those two Cmdlets, There will be two files generated in the log directory which we have pointed the parameter to save files to.

The CSV files have details about the two cmdlets and the HTTP Method they are utilizing in order to connect along the Request and response latency.

imageimage

This new version seems to be extremely useful esp in environments where such deep details are needed for troubleshooting issues.

Stay tuned for more

Reference:

https://docs.microsoft.com/en-us/powershell/exchange/exchange-online/exchange-online-powershell-v2/exchange-online-powershell-v2?view=exchange-ps

Use Group Based Licensing to Activate Office 365 Users

The Story

I got a request to place users into Security Groups for management purposes, The client have already users active but many of those users have left the work place and still have E3 or E1 Licenses which they should not have since this is pricey licenses and backing up users details is the easiest and most cost effective way of handling this.

So, To start (Prerequisites):

The Group based licensing management is a new feature, Was introduced in 2019 and not many people know that it is there however, This feature doesn’t come for free as you know (Since it’s Microsoft) and you must have a license for it or at least have users with E3 licensing model. So the requirements are:

  • – Azure AD Premium P1 or Higher
  • – Office 365 E3 or Higher.
  • – EMS or Higher.

How does it work?

In order for you to get this to work  you need to make sure you have planned from where you want to manage those groups and their licenses, Online? Or On-Premises?

IF Online

If you’re going to do this online, then you need to create a group for each Licensing Model which represents the intended License and its users e.g. Office365-E1 is going to be created as a security group and dedicated to E1 License users.

Office365-E3 will also be created the same way and users of License type E3 will be added to it.

If On-Premises

If you’re going to manage those groups on-premises, Then you must have ADConnect (Azure AD Sync) tool to sync those groups after creating them.

In my case I have created those groups in the following manner:

image

After creating those groups, You will need to sync them to Office 365 using ADConnect. To force this to sync immediately fire up Powershell on Azure Connect Server and type

Start-ADSyncSyncCycle -PolicyType delta

image

image

What If I have users already assigned with License?

If you have users already assigned licenses and want to manage them using Group Based licensing then you’re going to have to get a list of all your users with their Licenses information into a CSV file and Import those users to the groups you created base on the license they have.

I created a PowerShell that would match user’s names and based on the license mentioned in the CSV file would add them to the relevant group but first you need to export Users from Office 365.

Export Users and their license from Office 365

First of all we’ll connect to Office 365 MSOL Service using Online Powershell

image

Get-MsolUser -All |Where {$_.IsLicensed -eq $true } |Select DisplayName,UsageLocation,@{n="Licenses Type";e={$_.Licenses.AccountSKUid}},SignInName,UserPrincipalName,@{n="ProxyAddresses";e={$_.ProxyAddresses}}| Export-csv -Path C:ExportlicenseUsage.csv -notype

image

So this is how my CSV look right after I exported the users, We need to do some tuning on this CSV file to clean it and get it ready for our PowerShell.

image

There are total of 6 columns in this folder, If for whatever reason you wanted to use the ProxyAddress to distinguish users feel free to keep them in the script but in my case I didn’t need them so I deleted the entire column.

So I will keep the following (Remove Spacing between License Type)

  • DisplayName
  • UsageLocation
  • LicenseType
  • SignInName
  • UserPrincipalName

The Value of the License Type is usually formatted like this “TenantName: License” and in order to make this column useful I am going to remove the Tenant name from all the cells.

Find and Replace can easily remove and clean these values for you.

image

After cleaning the column, this is how it looks

image

This should be useful for us now along with the PowerShell to add the users to their relevant groups.

On Active Directory from an elevated PowerShell

Run PowerShell ISE  from a privileged account and copy + paste this script in ISE,

$ImportedUsers = Import-csv "C:\Users\AD\Desktop\ExportlicenseUsage.csv"

Foreach ($ImportedUser in $ImportedUsers){
$License = $ImportedUser.LicensesType
$E3 = "E3-Office365"
$E1 = "E1-Office365"
$EMS = "EMS-Office365"
$Sam = $ImportedUser.SamAccountName
$ImportedUPN = $ImportedUser.UserPrincipalName

$AllUsers = Get-ADUser -Filter * -Properties *
Foreach ($User in $AllUsers)
{
$UPN = $User.UserPrincipalName

if($user.UserPrincipalName -eq $ImportedUPN -and $License -match "EMS")
{
Add-ADGroupMember -Identity $EMS -Members $Sam
Write-Host $($UPN) "User has EMS License and has been added to the Group EMS" -ForegroundColor DarkGreen -BackgroundColor White
}
ElseIf ($user.UserPrincipalName -eq $ImportedUPN -and $License -Contains "STANDARDPACK")
{
Add-ADGroupMember -Identity $E1 -Members $Sam
Write-Host $($UPN) "User has E1 License and has been added to the Group E1" -ForegroundColor black -BackgroundColor green
}
ElseIf ($user.UserPrincipalName -eq $ImportedUPN -and $License -Contains "ENTERPRISEPACK")
{
Add-ADGroupMember -Identity $E3 -Members $Sam
Write-Host $($UPN) "User has E3 License and has been added to the Group E3" -ForegroundColor Blue -BackgroundColor White
}
}
}

image

Enabling Group Based License from Azure Portal

After this script finishes, I can open Azure Portal

From Azure Active Directory > Licenses > All Products

image   image    image

I will choose the license which I want to assign to a group of which I have created on my on-premises AD

image

Click on the License (Office 365 E1)  and choose Assign from top menu

image

Make sure you select assignment options and customize the license according to the products you want your group members to use then click on Users and Groups and select the relevant Group which you’ve created (In my case it’s E1-Office365)

image

Here, The group has been assigned

image

Click assign and you should be done

image

We will do the same for E3 Users

image

image

NOTE

From now on, Removing any user from this group will revoke their license and any service connected to it, You must be very careful when removing users from this group.

Microsoft has done great job covering this thoroughly and in a great detail including Scripts to be able to do many things like grabbing users who have an inherited license from a group or manually assigned. I am writing down the references if you’re more curious into these.

References:

https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/licensing-groups-assign

https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/licensing-ps-examples

Slow Migration – Office 365

The story:

In office 365 when you’re working on Exchange 2010,2013, 2016 or 2019 in a hybrid environment things might look easy but in a big enterprises where Internet security is something being taken into account very seriously. It might cause many issues that you don’t expect at all.

One of my clients whom I was doing Exchange Migration for had an issue with the Migration. The error was as follows:

Error occurs after Office 365 Exchange online connects to Exchange on-premises 2010 mailbox server

Error in Office 365

         : 20.

                                           27.04.2016 08:03:17 [DB3PR05MB0778] Transient error DataExportTransientExcep

                                           tion has occurred. The system will retry (2/1280).

                                           27.04.2016 08:04:53 [DB3PR05MB0778] The Microsoft Exchange Mailbox Replicati

                                           on service ‘DB3PR05MB0778.eurprd05.prod.outlook.com’ (15.1.466.25 caps:03FFF

                                           F) is examining the request.

                                           27.04.2016 08:04:55 [DB3PR05MB0778] Connected to target mailbox ‘lcwonline.o

                                           nmicrosoft.com\ec96e315-1059-4710-b358-1c4b42f3edeb (Primary)’, database ‘EU

                                           RPR05DG049-db131′, Mailbox server ‘DB3PR05MB0778.eurprd05.prod.outlook.com’

                                           Version 15.1 (Build 466.0).RequestExpiryTimestamp                   : 03.04.2116 07:42:38

ObjectState                              : New

Troubleshooting:

To troubleshoot issues, You need to put so many things into account! The architecture of the infrastructure of where you are doing the project is very important and the need of knowing how things are working matters.

Things that could always come in mind and handy are what you will need to start your troubleshooting:

– Bandwidth Limitations or Performance:

https://technet.microsoft.com/en-us/library/dn592150(v=exchg.150).aspx

https://technet.microsoft.com/en-us/library/jj200581(v=exchg.150).aspx

– Exchange Configuration (MRS)

To troubleshoot the MRs, You need to know what kind of error you’re getting and to see this you can use the following powershell after you connect to Office 365 powershell.

Get-MoveRequest {email} | Get-MoveRequestStatistics -Diagnostic -IncludeReport | Export-Clixml c:\logfile.xml

The resultant report will reveal the error and shows you where is the exact culprit.

– Disk Latency
– Firewall Configuration (IPS/IDS)

From Exchange 2016 to 2019 or 2013 to 2016 The transient error might be related to MRSProxy or at least this is the case with me 90% of the time. To resolve this issue you will need to change the MRSProxy values on the target server and depending on the error might also be the Source server too.

SOLUTION:

===========

1. Some instability was detected in communications as well as saturation by the size of the link.
2. The procedure to increase the timeout for the service through the file MRSProxy

File: MsExchangeMailboxReplication.exe.config

Object / line: DataImportTimeout.

New Value: 00:10:00

clip_image001[4]

New Configuration

clip_image001[6]

HOW TO GET ALL DOMAIN JOINED SERVER SERVICES THAT USING A UNIQUE OR DOMAIN USER

The Story (Finding Domain Joined Servers Services users)

If you’re wondering which of your servers are using domain joined account or a non regular account like network service or system. You will need to go through every server’s service console and check that one by one but thanks to PowerShell this job was made like a piece of cake.

Requirement

The requirement to run this script is a domain admin account since the PowerShell will require access to other servers using Remote PowerShell using Invoke command and run a Get-WMIObject script to find out those details. So in short I will write the required things for this to work

1- Logged in to Active Directory (In order for AD PowerShell module to run and find computers).

2- Domain admin account (To run the remote PowerShell on other servers and get service details)

3- Firewall for domain joined computers is open (To allow remote PowerShell to work) or have remote PowerShell enabled via GPO.

The Script will also show you the offline (inaccessible servers) and will state those servers as down as you can see in the screenshot below.

The script will also prompt you for a path to save the output. You can enter something like C:\Services.csv  as soon as you type the file path and extension it’ll be opened using Notepad.

image

#Check servers down and get services from the responsive servers

$Computers = Get-ADComputer -Filter { OperatingSystem -Like ‘*Windows Server*’}

$Input = ForEach ($computer in $computers){

$comp = $Computer.DNSHostName

$dist = $Computer.DistinguishedName

if (Test-Connection -Computername $comp -count 2 -Quiet )

{

Invoke-Command -ComputerName $comp -ScriptBlock {Get-WmiObject win32_service | where {$_.StartName -notlike “*LocalSystem*” -and $_.StartName -notlike “*LocalService*” -and $_.StartName -notlike “*NetworkService*” -and $_.StartName -notlike “*System*”} | select DisplayName,StartName,State }}

else{ Write-host $comp is down -foregroundColor red -BackGroundColor black

}

}

$Output = Read-Host “Enter File path and Name to save output to”

Out-File -FilePath $Output -InputObject $Input -Encoding ascii

Notepad $Output


image

image

2- SKYPE FOR BUSINESS EDGE SERVER DEPLOYMENT AND HYBRID INTEGRATION WITH SKYPE FOR BUSINESS ONLINE

Skype for Business Edge server deployment and Hybrid integration with Skype for Business Online

In the last Skype for Business post I have upgraded my Lync 2013 to Skype for Business (Click here to go to that post). in this article I am going to install Edge server for Skype for Business to the same Lync Environment where I have done the Upgrade to Skype for Business.

Configuring Edge Server

Setup NETBIOS

In order to configure Skype 4 Business Edge, we’ll have to change the Netbios to give it the name of our Domain but we won’t join it to the domain.

clip_image001[8]

clip_image002[8]

Setup NICs

Edge Server must have 2 NICs, one Local NIC will point out to the Front end server but must not have Default gateway so traffic can only flow through the DMZ out to the internet and back in. but still it must be able to ping to the FE from Edge and vice versa.

The DMZ network could have a single DMZ address (Public Address to be pointing to) or three DMZ addresses for public IP addresses with standard https ports.

clip_image003[8]

clip_image004[8]

Configure Hostnames

Edit the Edge server’s host file to include Lync FE and DC’s IP addresses and Hostname

image

Install Prerequisites

  • Microsoft .Net Framework 3.5
clip_image001[10]

Now I will go back to Skype for Business FE server, I’ll launch the topology builder and add new Edge server

I will add the first Edge pool which contains of a single Edge server

clip_image002[10]

Next, you will have to choose if you want to enable federation with partners or other service providers …e.g. (Google)

clip_image003[10]

I am intending to use a single Public IP address with a different ports (nonstandard) since this is a lab. For production use it’s recommended to have 3 public IP addresses, One is for Access Edge, AV and WebConf services.

clip_image004[10]

Next I will choose the last option which says that the Edge pool is translated by NAT. I will configure my firewall to NAT ports to the Edge’s DMZ IP addresses from the Public so I am choosing this option.

clip_image005[8]

clip_image006[8]

This is the FQDN’s the default configuration .. It’ll only use a single FQDN for all services if you’re going to use a single public IP address with a different ports.

IMPORTANT NOTE

When you use a single IP address with a different ports, the Access Edge port will normally change to 5061 (Not 443 like in the _sip._tls.domain.com) SRV record which will cause failure if you forgot to change this port to match the one in your Topology’s Access Edge settings.

Next I’ll have to enter my Edge server’s Local IP address.

clip_image007[8]

Next I will be asked to enter the DMZ’s IP address which the wizard calls (Private External IP address)

clip_image001[12]

Here I am going to place the NAT IP address which is my Public IP address.

clip_image002[12]

Next I’ll have to choose which Lync FE pool will be used as the next hop to the Edge pool. In this case I’ll be choosing my main pool since the second is only for resilience purpose.

clip_image003[12]

Then I’ll associate the mediation pool for Edge server for external media traffic. I can assign both in this case.

clip_image004[12]

Now I’ll click on Finish and right click on the Site name’s properties to enable the SIP federation and XMPP federation then Publish the topology.

clip_image005[10]

clip_image006[10]

clip_image007[10]

clip_image008[10]

Now I will setup Azure Active Directory Sync on my DC server in order to sync the required users for the test purpose.

My domain is adeo.local so I want to change the UPN for users to match the synced domain. (Adeo-office365.ga) and moh10ly.com

clip_image009[8]

Installing Azure Active Directory Sync

Now I will install the prerequisites which consist of the following

clip_image010[8]

Net framework 4.5.2 is required for AADS but it’s already installed on my server

clip_image011[8]

Next I will install Microsoft Online Service Sign in assistant

clip_image012[8]

Next I will install Azure AD Module

clip_image001[14]

Finally Azure AD Sync

clip_image002[14]

Before moving forward, I’ll have to go to the Office 365 portal and activate DirSync

clip_image003[14]

Then use a global admin credentials from O365.

clip_image004[14]

Adding the forest using an enterprise admin user account

clip_image005[12]

clip_image006[12]

Due to the fact that my domain adeo-office365.ga’s public dns host doesn’t have SRV configuration because it’s hosted by the famous free domain service (Freenom) so I’ll have to add my original domain moh10ly.com as Lync (S4B) requires SRV records to point to the on-premises lync.

clip_image007[12]

clip_image008[12]

clip_image001[16]

clip_image002[16]

clip_image003[16]

I will only sync one OU, so I will untick the Sync now box and click on Finish

clip_image004[16]

I will go to the following path

“C:\Program Files\Microsoft Azure AD Sync\UIShell” and create a shortcut for the GUI application of AADS on the desktop

“C:\Program Files\Microsoft Azure AD Sync\UIShell\miisclient.exe”

clip_image005[14]

To get this GUI app to work, you will have to sign out of your account and sign back in as your username will be added to the local administrators and have the authority to open it

Log off, log back in

clip_image006[14]

Next I will go to the connectors tab and double click on the ADDS connector (Adeo.local)

clip_image007[14]

I will go to the Configure Directory Partitions and under Credentials I’ll choose “Alternate credentials for this directory partition” then enter my on-premises AD Enterprise admin credentials

clip_image008[14]

I’ll click on Containers

clip_image001[18]

I’ll untick the DC=Adeo,Dc=Local box and only choose Dirsync OU then click OK and apply

clip_image002[18]

Before I start syncing my AD , I will go to Skype for Business Server and add my domain moh10ly.com as a SIP domain

clip_image003[18]

Next I am going to change the FQDN of the SIP access edge for public domain to moh10ly.com and the default port for the Access Edge to 443 and publish the topology

clip_image004[18]

clip_image005[16]

I needed to finally check if all my FE servers are replicating. So then I can move to Edge server to install Lync components

clip_image006[16]

On the Edge server, I’ll use ISO for Skype 4 business to install the setup

clip_image007[16]

clip_image008[16]

First thing I’ll install the local Configuration Store

I’ll click on Run and then I’ll be asked to import the configuration file which I’ll must export from Lync FE (Skype 4 b FE) server

clip_image009[10]

In this case, I’ll go to Lync FE and open Lync Management shell and enter the following Cmdlet

Export-CsConfiguration -FileName c:\top.zip

clip_image010[10]

This cmdlet will export a file to the root C drive . I’ll copy this file to the edge server.

clip_image011[10]

I’ll click next to continue, this should start installing the local store

clip_image012[10]

clip_image013[8]

clip_image014[8]

Next I’ll request a certificate for Internal NIC For edge server

clip_image015[8]

clip_image016[8]

clip_image017[8]

Configure Certificate

I’ll take the CSR (Certificate sign request) code and get a certificate from my local CA

clip_image018[8]

I’ll open MMC and add Certificates console and import the PKCS certificate

clip_image001[20]

clip_image002[20]

After importing the certificate I’ll assign it to the internal NIC by clicking on Assign to the Edge Internal

clip_image003[20]

clip_image004[20]

clip_image005[18]

clip_image006[18]

Once we assign the certfiicate to the internal edge. The replication service for Edge and FE will start working

clip_image007[18]

Now I’ll import my Public Certificate to Edge Server’s DMZ NIC

I already imported my public certificate, now I’ll go to the S4B wizard and assign it there

clip_image008[18]

clip_image009[12]

Unlike IN lync 2013 when you Click on Start service in the Wizard all services start on their own but on Skype for business you ‘ll have to start the services manually by yourself.

clip_image010[12]

So Instead I used the service console to start the services.

Now I’ll go back to the FE And enable remote connectivity to Skype for Business from outside and make sure that replication works fine by checking the Topology or from cmdlet

clip_image011[12]

clip_image012[12]


After the replication is finished, I was able to login remotely with my Skype for Business on-premises accounts.

Setting up Hybrid integration with Skype online for Business (O365)

https://technet.microsoft.com/en-us/library/jj205126.aspx

https://technet.microsoft.com/en-us/library/jj204669.aspx

In order to allow Hybrid environment to function properly, we’ll have to federate our Skype for Business on-premises’s Edge server as Microsoft says below

Federation allows users in your on-premises deployment to communicate with Office 365 users in your organization. To configure federation, run the following cmdlets in the Skype for Business Server Management Shell:

From <https://technet.microsoft.com/en-us/library/jj205126.aspx>

On the front end server, we’ll run the following CMDlet

Set-CSAccessEdgeConfiguration -AllowOutsideUsers 1 -AllowFederatedUsers 1 -UseDnsSrvRouting -EnablePartnerDiscovery $true

clip_image014[10]

Next cmdlet will create a new public federated provider for skype for business online.. However it already exists by default as in the below snapshot but just to avoid any issues I will delete the default provider from control panel and recreate it again. 

clip_image015[10]

I’ll delete the hosted provider “Skype for Business Online”

clip_image016[10]

I’ll try the cmdlet again after deleting the provider ..

New-CSHostingProvider -Identity SkypeforBusinessOnline -ProxyFqdn “sipfed.online.lync.com” -Enabled $true -EnabledSharedAddressSpace $true -HostsOCSUsers $true -VerificationLevel UseSourceVerification -IsLocal $false -AutodiscoverUrl https://webdir.online.lync.com/Autodiscover/AutodiscoverService.svc/root

clip_image017[10]

Since it worked already, I will go back to the control panel and make sure it is enabled

clip_image018[10]

Next is : Configure your Skype for Business Online tenant for a shared SIP address space

Note:

To configure a shared SIP address space, establish a remote PowerShell session with Skype for Business Online, and then run the following cmdlet:

We’ll have to download skype for business online powershell

https://onedrive.live.com/redir?resid=82488EABA4ACDB15!38849&authkey=!AKW6Ln4Rkn6QuUI&ithint=file%2cexe

After launching the PowerShell module as an administrator I’ll run the following cmdlet

Import-Module SkypeOnlineConnector

clip_image019[8]

Now I’ll connect to my Office 365 tenant

clip_image020[8]

$cred = Get-Credential

$CSSession = New-CsOnlineSession -Credential $cred

Import-PSSession $CSSession -AllowClobber

clip_image021[8]

Now I’ll configure the shared sip address

Set-CsTenantFederationConfiguration -SharedSipAddressSpace $true

From <https://technet.microsoft.com/en-us/library/jj205126.aspx>

clip_image001[22]

To double check my configuration I will see if the SharedSipAddresSpace is enabled or not

Get-CsTenantFederationConfiguration

clip_image002[22]

To double check that the hybrid configuration is setup properly we can use the Skype for business on-premises Hybrid UI wizard from the Home Menu under “Connection to Skype for Business Online”

clip_image003[22]

Using the Skype for Business 2015 User interface to setup Hybrid configuration:

After you sign in it does automatically logs you in and configure the three following options

  1. Federation for the Edge server
  2. Federation with Office 365.
  3. Shared SIP address space.
clip_image004[22]

clip_image005[20]

Now I will configure my DNS Settings as recommended by Microsoft for the Hybrid Integration scenario

DNS Settings

When creating DNS SRV records for hybrid deployments, the records, _sipfederationtls._tcp.<domain> and _sip._tls.<domain>, should point to the on-premises Access Proxy.

From <https://technet.microsoft.com/en-us/library/jj205403.aspx>

  1. Update some DNS records to direct all SIP traffic to Skype for Business on-premises:
  • The lyncdiscover.contoso.com A record to point to the FQDN of the on-premises reverse proxy server.
  • Update the _sip._tls.contoso.com SRV record to resolve to the public IP or VIP address of the Access Edge service of Skype for Business on-premises.
  • Update the _sipfederationtls._tcp.contoso.com SRV record to resolve to the public IP or VIP address of the Access Edge service of Skype for Business on-premises.
  • If your organization uses split DNS (sometimes called “split-brain DNS”), make sure that users resolving names through the internal DNS zone are directed to the Front End Pool.

From <https://support.office.com/en-us/article/Configure-Skype-for-Business-Server-2015-Hybrid-b06ee805-4349-4519-82fb-b06ed57c0bd0>

According to Microsoft’s configuration of the Public DNS, you will have to configure only the SRV records to point to your edge server however, running a simple wireshark on your Skype for business client machine you can notice the following:

clip_image006[20]

Microsoft Lync / Skype client first requires the Lyncdiscover / Lyncdiscoverinternal record in order to see where the user is located… then gets redirected to webdir.online.lync.com which is the Cname value to the Lyncdiscover Cname in the public DNS and tries to login the user through Login.microsoftonline.com then finds no user there and logs in using the SRV eventually in the end as in the below snapshot which I’ve used Wireshark for to monitor the DNS traffic that the Lync Client requests upon login request.

clip_image007[20]

NOTE:

What have me confused here is that Microsoft says only SRV records must be pointing to your On-premises Lync/Skype for Business Edge server.. So you must enter something else other than SIP.domain.com (Which in normal cases might be the common name of your Edge certificate) for the value of the SRV Record since the SIP.domain.com and Lyncdiscover.domain.com must be pointing to Office 365.

I tried using the Public IP address of my Edge server just to check if my on-premises user will connect without any issue however I did have an issue with the Certificate saying “There was a problem verifying the certificate from the server”.

clip_image008[20]

Error:

Luckily the Public certificate that I had on my edge server had multiple SANs (Subject Alternative Names) and one of them was WAC.moh10ly.com which I was intending to use for the WAC Server (Office Web Apps Server) and then I created an A record on my public DNS WAC.moh10ly.com that points to my Edge server’s Public IP address…. although the Wac.moh10ly.com is not a common name but it worked and I was able to federate with Office 365 users and was able to move users from on-premises to office 365 and back to on-premises as demonstrated later in the article.

“When creating DNS SRV records for hybrid deployments, the records, _sipfederationtls._tcp.<domain> and _sip._tls.<domain>, should point to the on-premises Access Proxy.”

From <https://support.office.com/en-us/article/Configure-Skype-for-Business-Server-2015-Hybrid-b06ee805-4349-4519-82fb-b06ed57c0bd0>

clip_image009[14]

Now I have changed all the SRV records to direct to the new A record

clip_image010[14]

And finally deleted the A sip record and created a new CNAME record that points to sipdir.online.lync.com

clip_image011[14]

clip_image012[14]

I have already a user synced from my local AD to the cloud (office 365) that’s not enabled for Skype for business on-premises .. Once this user is synced and have been assigned a license it should be directly enabled for Skype for Business Online and I should be able to sign in to it without any issue.

Note:

In order for both users (homed online and On-premises) to see eachother’s presence the synced user must be enabled on the On-premises Server before moved to the cloud or else the presence and M will fail.

Time to test, I was able to sign in to the Online homed user (admin) and now I’ll be adding the on-premises homed user to the list to check the presence, IM ..etc

clip_image001[24]

Here I added the user admin to my other account Mohammed.hamada and vice versa.

clip_image002[24]

The Presence appears to be working fine for user homed on-premises as it shows when I changed it to “busy, be right back..etc” on the cloud user’s Client however the Office 365 homed user’s presence takes time to change on the on-premises user’s list and the IM doesn’t seem to work properly as messages sometimes doesn’t go through and fail.

Sending a message from the on-premises User (Mohammed Hamada) to (ADMIN)

clip_image003[24]

Now sending an IM from Admin to Mohammed Hamada

clip_image004[24]

To make sure that the issue is not within my on-premises server, I will use a different Skype for Business online account and see if IM work both ways.

This is my other user.. The presence information seems to work properly and now I’ll test the IM

clip_image005[22]

IM between my On-premises and another user on another Office 365 tenant seems to be working fine back and forth as in the below snapshots so the issue might be related to Office 365 tenant which I am using for this test (could be related to trial version)

I am going to open a case with MS and see why this issue happens since my on-premises work fine with other tenants.

clip_image006[22]

clip_image007[22]

Now It’s time to move users from and to cloud and on-premises to check how easy, flexible or hard this process is.

I currently have 2 users, one on cloud and one synced and homed online (Office 365)

clip_image008[22]

In order to move users, you can go to Users tab after the hybrid config is finished and find the user you want to move then click on Actions and chose to move the users to the Skype for Business Online as in the below snapshot

Note:

Before you move the user to Office 365, you must assign license to the user or else the move will fail.

clip_image009[16]

clip_image010[16]

clip_image011[16]

clip_image012[16]

clip_image013[12]

You can move the user back from Office 365 to your on-premises Skype for Business server with the same process exactly except that you’ll have to choose which pool you need to move the user to.

Checking where the user is hosted from Skype for business Management shell

The Hosting Provider will show you where the user is working from now.

clip_image014[12]

clip_image015[12]

clip_image016[12]

Hope this has been helpful

References:

https://technet.microsoft.com/en-us/library/jj204967.aspx

https://technet.microsoft.com/en-us/library/jj205403.aspx

https://technet.microsoft.com/en-us/library/jj205126.aspx

https://technet.microsoft.com/en-us/library/jj204669.aspx

https://support.office.com/en-us/article/Configure-Skype-for-Business-Server-2015-Hybrid-b06ee805-4349-4519-82fb-b06ed57c0bd0

https://channel9.msdn.com/Events/Ignite/2015/BRK4129