I have a Powershell script that is run on a Windows 2008 R2 server with Exchange Server 2010 console installed on it. The script, pmduaactivesync.ps1, is run from Task scheduler, so it has to be called using a weird command rather than just calling it directly. Here is how it is run:
powershell -PSConsoleFile "C:\Program Files\Microsoft\Exchange Server\v14\bin\exshell.psc1" -exec bypass -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange.ps1'; &'C:\dev\csom\pmduaactivesync.ps1'"
The script is being run as a service account, and that account has all the access it needs to make changes in the Exchange environment.
Now, in the script, at one point I am trying to set the Exchange ActiveSync attribute on a mailbox to True. Here is that part of the code
# Try setting ActiveSync to true
try {
Set-CASMailbox -Identity $tempUsername -ActiveSyncEnabled $true
if ($?) {
# Set ASChangeValue to 1 (to be used when updating SP List)
$ASChangeValue="1"
} else {
throw $error[0].Exception
}
} catch {
Write-Host "Exception caught with 'Set-CASMailbox -Identity $tempUsername -ActiveSyncEnabled $true' command." -ForegroundColor Red
Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
$ASChangeValue="8"
}
In the script, I'm also creating a transcript using the Start-Transcript cmdlet.
Here is my problem. The Set-CASMailbox cmdlet is throwing an error, shown below:
WARNING: The cmdlet extension agent with the index 1 has thrown an exception in OnComplete(). The exception is:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.Exchange.Data.Storage.ExchangePrincipal.get_ServerFullyQualifiedDomainName()
at Microsoft.Exchange.Data.Storage.MailboxSession.Initialize(MapiStore linkedStore, LogonType logonType,
ExchangePrincipal owner, DelegateLogonUser delegateUser, Object identity, OpenMailboxSessionFlags flags,
GenericIdentity auxiliaryIdentity)
at Microsoft.Exchange.Data.Storage.MailboxSession.<>c__DisplayClass12.<CreateMailboxSession>b__10(MailboxSession
mailboxSession)
at Microsoft.Exchange.Data.Storage.MailboxSession.InternalCreateMailboxSession(LogonType logonType,
ExchangePrincipal owner, CultureInfo cultureInfo, String clientInfoString, IAccountingObject budget, Action`1
initializeMailboxSession, InitializeMailboxSessionFailure initializeMailboxSessionFailure)
at Microsoft.Exchange.Data.Storage.MailboxSession.CreateMailboxSession(LogonType logonType, ExchangePrincipal owner,
DelegateLogonUser delegateUser, Object identity, OpenMailboxSessionFlags flags, CultureInfo cultureInfo, String
clientInfoString, PropertyDefinition[] mailboxProperties, IList`1 foldersToInit, GenericIdentity auxiliaryIdentity,
IAccountingObject budget)
at Microsoft.Exchange.Data.Storage.MailboxSession.ConfigurableOpen(ExchangePrincipal mailbox, MailboxAccessInfo
accessInfo, CultureInfo cultureInfo, String clientInfoString, LogonType logonType, PropertyDefinition[]
mailboxProperties, InitializationFlags initFlags, IList`1 foldersToInit, IAccountingObject budget)
at Microsoft.Exchange.Data.Storage.MailboxSession.OpenAsSystemService(ExchangePrincipal mailboxOwner, CultureInfo
cultureInfo, String clientInfoString)
at Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLogMessageData data,
LogMessageDelegate logMessage)
at Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boolean succeeded, Exception e)
at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task, Boolean succeeded, Exception exception)
I'm not 100% on this, but since the error is referencing "The cmdlet extension agent with the index 1" I ran Get-CmdletExtensionAgent to see what that might be. After running the command, assuming I'm reading it correctly, it is referencing the Query Base DN Agent.
>Get-CmdletExtensionAgent | Format-Table Name, Enabled, Priority
Name Enabled Priority
---- ------- --------
Admin Audit Log Agent True 255
Query Base DN Agent True 1
Rus Agent True 2
Mailbox Resources Management Agent True 3
Provisioning Policy Agent True 4
OAB Resources Management Agent True 5
Scripting Agent False 6
Mailbox Creation Time Agent True 0
Here is my big question,
Why is this exception not getting caught?
Later in my script, $ASChangeValue is still set to 1, as opposed to 8. Any help on this would be appreciated, thanks.
Add -ErrorAction Stop to Set-CASMailbox:
Set-CASMailbox -Identity $tempUsername -ActiveSyncEnabled $true -ErrorAction Stop
Related
I usually run a modified version of the script provided by Microsoft on how to “Convert per-user MFA enabled and enforced users to disabled”.
If I run it interactively, the cmdlet “Connect-MsolService” works like a charm. However, as soon as I tried to use the parameters “AdGraphAccessToken” and “MsGraphAccessToken” it throws the following errors:
Connect-MsolService : An unexpected error occurred.
At line:1 char:1
+Connect-MsolService -AdGraphAccessToken $AadAccessToken -MsGraphAcces ...
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
+FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.InvalidHeaderException,Microsoft.Online.Administration.Automation.ConnectMsolService
Connect-MsolService : Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
At line:1 char:1
+Connect-MsolService -AdGraphAccessToken $AadAccessToken -MsGraphAcces ...
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
+FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.MicrosoftOnlineException,Microsoft.Online.Administration.Automation.ConnectMsolService
When passing the same tokens to the cmdlet “Connect-AzureAD”, it goes as expected.
I use the following snippet for acquiring the tokens:
$TenantId = 'MyTenantId'
$Authority = 'https://login.microsoftonline.com/{0}/oauth2/v2.0/token' -f $TenantId
$ClientId = 'MyAzureActiveDirectoryAppId'
$ClientSecret = 'MyAzureActiveDirectoryAppSecret'
$Parameters =
#{
Authority = $Authority
ClientId = $ClientId
ClientSecret = (ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force)
}
$AadAccessToken = (Get-MsalToken #Parameters -Scopes 'https://graph.windows.net/.default').AccessToken
$MsAccessToken = (Get-MsalToken #Parameters -Scopes 'https://graph.microsoft.com/.default').AccessToken
#Connect-AzureAD -AadAccessToken $AadAccessToken -MsAccessToken $MsAccessToken -AccountId $ClientId -TenantId $TenantId
Connect-MsolService -AdGraphAccessToken $AadAccessToken -MsGraphAccessToken $MsAccessToken -AzureEnvironment AzureCloud
I know that the modules MSOnline a AzureAD have been deprecated in favor of Microsoft.Graph, but since there is no other programmatic way to Enable per-user MFA I would kindly ask you people for some guidance: am I missing something here?
There is a way to create phoneAuthenticationMethod MFA using the MS graph which is still in beta phase:
https://learn.microsoft.com/en-us/graph/api/authentication-post-phonemethods?view=graph-rest-beta&tabs=powershell
Actually, the error doesn't raise if I just run (Command ^C^C) from a lisp script.
The case is, my app is a .NET app, and I call some SendStringToExecute to use some lisp code.
To be sure to end the lisp routine, I put at the end:
doc.SendStringToExecute("(Command ^C^C)", True, False, True)
The result of Forge Design Automation is: failedinstruction
Though I can easily find another way to get around this, it cost me more than a day to figure out that it was the (Command ^C^C) cause the failedinstruction, while everything else was working fine.
Hope this bug will be fixed as well as anything similar won't raise up again somewhere else.
I isolate the case like this:
Make a .NET bundle, or just reuse any of your existing one in debug mode
Add the following lisp define function (or it can be a custom command, whatever):
<LispFunction("l+SendStringToExecute")>
Public Shared Function lsp_SendStringToExcute(args As ResultBuffer) As Object
Dim script$ = Nothing
For Each arg As TypedValue In args.AsArray
script = arg.Value
Exit For
Next
script = script.Trim()
If script <> "" Then
Document doc =
AcadApplication.DocumentManager.MdiActiveDocument
doc.SendStringToExecute(script + vbCr, True, False, True)
End If
Return New TypedValue(LispDataType.T_atom)
End Function
Upload the bundle to Forge, create a dump activity and just run the custom lisp solely:
(l+SendStringToExecute "(Command ^C^C)")
The result log is here like this:
...
[02/01/2021 17:23:26] Command: (l+SendStringToExecute "(Command ^C^C)")
[02/01/2021 17:23:26] T
[02/01/2021 17:23:26] Command: (Command ^C^C)
[02/01/2021 17:23:26] *Cancel*
[02/01/2021 17:23:26] Command: nil
[02/01/2021 17:23:27] End AutoCAD Core Engine standard output dump.
[02/01/2021 17:23:27] Error: AutoCAD Core Console failed to finish the script - an unexpected input is encountered.
[02/01/2021 17:23:27] End script phase.
[02/01/2021 17:23:27] Error: An unexpected error happened during phase CoreEngineExecution of job.
[02/01/2021 17:23:27] Job finished with result FailedExecution
[02/01/2021 17:23:27] Job Status:
{
"status": "failedInstructions", ...
Thanks for reporting, I'm not sure if we allow command expression in accoreconsole.
The suggestion is to use following way.
[CommandMethod("CANCELOUTSTANDING")]
public void TESTCANCEL()
{
var doc = Application.DocumentManager.MdiActiveDocument;
string cmd = string.Format("{0}", new string((char)03, 2));
doc.SendStringToExecute(cmd, true, false, true);
}
Here I am trying to use a plugin to check whether the service running or not, if there is any warning or any critical action required, at the same time the performance parameter.
We have used below plugin to check if a server is alive or not and read it's performance data JSON
https://github.com/drewkerrigan/nagios-http-json
I am trying to read a JSON file as below which is hosted on http://localhost:8080/sample.json
The plugin works perfectly on Command line, it shows me all the Metrics available.
$:/usr/lib/nagios/plugins$ ./check_http_json.py -H localhost:8080 -p sample.json -m metrics.etp_count metrics.atc_count
OK: Status OK.|'metrics.etp_count'=101 'metrics.atc_count'=0
But when I try the same in Icinga2 configuration, it doesn't show me this performance metrics, although it doesn't give any error but at the same time it don't show any value.
find the JSON, Command.conf and Service.conf as follows.
{
"metrics": {
"etp_count": "0",
"atc_count": "101",
"mean_time": -1.0,
}
}
Below are my commands.conf and services.conf
commands.conf
/* Json Read Command */
object CheckCommand "json_check"{
import "plugin-check-command"
command = [PluginDir + "/check_http_json.py"]
arguments = {
"-H" = "$server_port$"
"-p" = "$json_path$"
"-w" = "$warning_value$"
"-c" = "$critical_value$"
"-m" = "$Metrics1$,$Metrics2$"
}
}
services.conf
apply Service "json"{
import "generic-service"
check_command = "json_check"
vars.server_port="localhost:8080"
vars.json_path="sample.json"
vars.warning_value="metrics.etp_count,1:100"
vars.critical_value="metrics.etp_count,101:1000"
vars.Metrics1="metrics.etp_count"
vars.Metrics2="metrics.atc_count"
assign where host.name == NodeName
}
Does any one have any idea how can we pass multiple values in Command.conf and Service.conf??
I have resolved the issue.
I had to change the Plugin file "check_http_json.py" for below code
def checkMetrics(self):
"""Return a Nagios specific performance metrics string given keys and parameter definitions"""
metrics = ''
warning = ''
critical = ''
if self.rules.metric_list != None:
for metric in self.rules.metric_list:
Replaced With
def checkMetrics(self):
"""Return a Nagios specific performance metrics string given keys and parameter definitions"""
metrics = ''
warning = ''
critical = ''
if self.rules.metric_list != None:
for metric in self.rules.metric_list[0].split():
Actually the issue was the list was not handled properly, so it was not able to iterate through the items in the list, it was considering it as a single string due to services.config file.
it had to be further get split to get the items in the Metrics string.
What I have:
GNU/Linux host
nginx is up and running
there is a cron-job scheduled to run immediately after a specific file has been removed (similar to run-crons)
GitHub sends a webhook when someone pushes to a repository
What I want:
I do now want to run either lua or anything comparable to parse GitHub's request and validate it and then delete a file (if the request was valid of course).
Preferably all of this should happen without the hassle to maintain an additional PHP installation as there is currently none, or the need to use fcgiwrap or similar.
Template:
On the nginx side I have something equivalent to
location /deploy {
# execute lua (or equivalent) here
}
To read json body of GH webhook you nead use JSON4Lua lib, and to validate HMAC signature use luacrypto.
Preconfigure
Install required modules
$ sudo luarocks install JSON4Lua
$ sudo luarocks install luacrypto
In Nginx define location for deploy
location /deploy {
client_body_buffer_size 3M;
client_max_body_size 3M;
content_by_lua_file /path/to/handler.lua;
}
The max_body_size and body_buffer_size should be equal to prevent error
request body in temp file not supported
https://github.com/openresty/lua-nginx-module/issues/521
Process webhook
Get request payload data and check is correct
ngx.req.read_body()
local data = ngx.req.get_body_data()
if not data then
ngx.log(ngx.ERR, "failed to get request body")
return ngx.exit (ngx.HTTP_BAD_REQUEST)
end
Verify GH signature with use luacrypto
local function verify_signature (hub_sign, data)
local sign = 'sha1=' .. crypto.hmac.digest('sha1', data, secret)
-- this is simple comparison, but it's better to use a constant time comparison
return hub_sign == sign
end
-- validate GH signature
if not verify_signature(headers['X-Hub-Signature'], data) then
ngx.log(ngx.ERR, "wrong webhook signature")
return ngx.exit (ngx.HTTP_FORBIDDEN)
end
Parse data as json and check is master branch, for deploy
data = json.decode(data)
-- on master branch
if data['ref'] ~= branch then
ngx.say("Skip branch ", data['ref'])
return ngx.exit (ngx.HTTP_OK)
end
If all correct, call deploy function
local function deploy ()
-- run command for deploy
local handle = io.popen("cd /path/to/repo && sudo -u username git pull")
local result = handle:read("*a")
handle:close()
ngx.say (result)
return ngx.exit (ngx.HTTP_OK)
end
Example
Example constant time string compare
local function const_eq (a, b)
-- Check is string equals, constant time exec
getmetatable('').__index = function (str, i)
return string.sub(str, i, i)
end
local diff = string.len(a) == string.len(b)
for i = 1, math.min(string.len(a), string.len(b)) do
diff = (a[i] == b[i]) and diff
end
return diff
end
A complete example of how I use it in github gist https://gist.github.com/Samael500/5dbdf6d55838f841a08eb7847ad1c926
This solution does not implement verification for GitHub's hooks and assumes you have the lua extension and the cjson module installed:
location = /location {
default_type 'text/plain';
content_by_lua_block {
local cjson = require "cjson.safe"
ngx.req.read_body()
local data = ngx.req.get_body_data()
if
data
then
local obj = cjson.decode(data)
if
# checksum checking should go here
(obj and obj.repository and obj.repository.full_name) == "user/reponame"
then
local file = io.open("<your file>","w")
if
file
then
file:close()
ngx.say("success")
else
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
else
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
else
ngx.exit(ngx.HTTP_NOT_ALLOWED)
end
}
}
I compiled Bind 9 from source (see below) and set up Bind9 with MySQL DLZ.
I keep getting an error when I attempt to fetch anything from the server about buffer overflow. I've googled many times but can not find anything on how to fix this error.
Configure options:
root#anacrusis:/opt/bind9/bind-9.9.1-P3# named -V BIND 9.9.1-P3 built
with '--prefix=/opt/bind9' '--mandir=/opt/bind9/man'
'--infodir=/opt/bind9/info' '--sysconfdir=/opt/bind9/config'
'--localstatedir=/opt/bind9/var' '--enable-threads'
'--enable-largefile' '--with-libtool' '--enable-shared'
'--enable-static' '--with-openssl=/usr' '--with-gssapi=/usr'
'--with-gnu-ld' '--with-dlz-postgres=no' '--with-dlz-mysql=yes'
'--with-dlz-bdb=no' '--with-dlz-filesystem=yes' '--with-dlz-stub=yes'
'--with-dlz-ldap=yes' '--enable-ipv6' 'CFLAGS=-fno-strict-aliasing
-DDIG_SIGCHASE -O2' 'LDFLAGS=-Wl,-Bsymbolic-functions' 'CPPFLAGS=' using OpenSSL version: OpenSSL 1.0.1 14 Mar 2012 using libxml2
version: 2.7.8
This is the error I get when I dig example.com (with debug):
Query String: select ttl, type, mx_priority, case when
lower(type)='txt' then concat('"', data, '"')
else data end from dns_records where zone = 'example.com' and host = '#'
17-Sep-2012 01:09:33.610 dns_rdata_fromtext: buffer-0x7f5bfca73360:1:
unexpected end of input 17-Sep-2012 01:09:33.610 dns_sdlz_putrr
returned error. Error code was: unexpected end of input 17-Sep-2012
01:09:33.610 Query String: select ttl, type, mx_priority, case when
lower(type)='txt' then concat('"', data, '"')
else data end from dns_records where zone = 'example.com' and host = '*'
17-Sep-2012 01:09:33.610 query.c:2579: fatal error: 17-Sep-2012
01:09:33.610 RUNTIME_CHECK(result == 0) failed 17-Sep-2012
01:09:33.610 exiting (due to fatal error in library)
Named.conf
options {
directory "/opt/bind9/";
allow-query-cache { none; };
allow-query { any; };
recursion no;
};
dlz "Mysql zone" {
database "mysql
{host=localhost dbname=system ssl=false user=root pass=*password*}
{select zone from dns_records where zone = '$zone$'}
{select ttl, type, mx_priority, case when lower(type)='txt' then concat('\"', data, '\"')
else data end from dns_records where zone = '$zone$' and host = '$record$'}
{}
{}
{}
{}";
};
Do you run named single-threaded (with "-n 1" parameter)? If not, named will crash in various places when working on more than one query in parallel, since the MySQL DLZ module is not thread safe.
Manually log into the DB and run the query. See what it comes up with. The error says it's got an unexpected end of input, meaning it was expecting to get something and it never got it. So the first thing is to see if it you can get it manually. Maybe the mysqld isn't running. Maybe the user isn't defined or password is set wrong or permissions are not granted on that table. These could all account for the error.
Assuming all this works then you have two options: Enable more logging in your named.conf so you have more data to work with on what's happeningRemove and reinstall BIND, ensuring that all hashes match on all libraries and that all dependancies are in place.
I have gotten Bind with DLZ working on CentOS 7. I do not get the error that is effecting you.
I realize this is an older post but I thought I would share my conf files , and configure options.
I am using Bind 9.11.0
configure
./configure --prefix=/usr --sysconfdir=/etc/bind --localstatedir=/var --mandir=/usr/share/man --infodir=/usr/share/info --enable-threads --enable-largefile --with-libtool --enable-shared --enable-static --with-openssl=/usr --with-gssapi=/usr --with-gnu-ld --with-dlz-postgres=no --with-dlz-mysql=yes --with-dlz-bdb=no --with-dlz-filesystem=yes --with-dlz-stub=yes --enable-ipv6
named.conf
// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local
#auskommentiert !!!
#include "/etc/bind/named.conf.options";
#include "/etc/bind/named.conf.local";
#include "/etc/bind/named.conf.default-zones";
key "rndc-key" {
// how was key encoded
algorithm hmac-md5;
// what is the pass-phrase for the key
secret "noway";
};
#options {
#default-key "rndc-key";
#default-server 127.0.0.1;
#default-port 953;
#};
controls {
inet * port 953 allow { any; } keys { "rndc-key"; };
#inet * port 53 allow { any; } keys { "rndc-key"; };
};
logging {
channel query.log {
file "/var/log/query.log";
// Set the severity to dynamic to see all the debug messages.
severity dynamic;
};
category queries { query.log; };
};
dlz "Mysql zone" {
database "mysql
{host=172.16.254.100 port=3306 dbname=dyn_server_db user=db_user pass=db_password}
{SELECT zone FROM dyn_dns_records WHERE zone = '$zone$'}
{SELECT ttl, type, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data
FROM dyn_dns_records
WHERE zone = '$zone$' AND host = '$record$' AND type <> 'SOA' AND type <> 'NS'}
{SELECT ttl, type, data, primary_ns, resp_person, serial, refresh, retry, expire, minimum
FROM dyn_dns_records
WHERE zone = '$zone$' AND (type = 'SOA' OR type='NS')}
{SELECT ttl, type, host, mx_priority, IF(type = 'TXT', CONCAT('\"',data,'\"'), data) AS data, resp_person, serial, refresh, retry, expire, minimum
FROM dyn_dns_records
WHERE zone = '$zone$' AND type <> 'SOA' AND type <> 'NS'}
{SELECT zone FROM xfr_table where zone='$zone$' AND client = '$client$'}";
};