Access Denied when accessing WebDav resource from service - c

I have a service on Windows 2003 Server that needs to access a webdav resource as a UNC Path. The purpose of this service is to verify (and take corrective actions) webdav functionality to sharepoint. The idea is to write a file to sharepoint, and verify it's contents. If something goes wrong and the threshold was exceeded the mrxdav and webclient service will be restarted.
I run the service under a service account that is local admin on the 2003 server and has access to the sharepoint "folder". (I verified this by logging in with the service account and write a file to the same folder).
When the service tries to write a file to this folder it fails with ACCESS DENIED, process monitor shows that the service runs under LocalSystem and Impersonates my service account
I also tried to Impersonate the service account from my code using LogonUser and LogonUserEx (with the various options for logon interactive, network, network cleartext and providers) followed by ImpersonateUser but all result in the same ACCESS DENIED.
I presume this is something specific to a service using the WebClient service.
My code is written in Delphi but I've added the c tags as well to attract more readers since I don't think my problem is Delphi related.
EDIT: Perhaps relevant, I am running a seperate Thread that actually accesses the WebDav share.
EDIT: As a workaround I am create a network connection using explicit credentials using the following code:
function TGuardThread.Map(const Username: String; var Password: String;
const Domain: String): Boolean;
var
nr: NETRESOURCE;
dwRes: DWORD;
begin
try
ZeroMemory(#nr, SizeOf(nr));
nr.dwType := RESOURCETYPE_ANY;
nr.lpRemoteName := PChar('\\mywebdavroot\myfolder');
dwRes := WNetAddConnection2(nr, PChar(Password),
PChar(Format('%s\%s', [Domain, Username])), CONNECT_UPDATE_PROFILE);
Result := dwRes = NO_ERROR;
finally
if Length(Password) > 0 then
SecureZeroMemory(#Password[1], Length(Password) * SizeOf(Char));
end;
end;

Workaround is to use an explicit connection with credentials to the WebDav server, like this:
function TGuardThread.Map(const Username: String; var Password: String;
const Domain: String): Boolean;
var
nr: NETRESOURCE;
dwRes: DWORD;
begin
try
ZeroMemory(#nr, SizeOf(nr));
nr.dwType := RESOURCETYPE_ANY;
nr.lpRemoteName := PChar('\\mywebdavroot\myfolder');
dwRes := WNetAddConnection2(nr, PChar(Password),
PChar(Format('%s\%s', [Domain, Username])), CONNECT_UPDATE_PROFILE);
Result := dwRes = NO_ERROR;
finally
if Length(Password) > 0 then
SecureZeroMemory(#Password[1], Length(Password) * SizeOf(Char));
end;
end;

Related

H2 database login issues

I am using a local file based H2 Hibernate database with Grails.
I have two separate file type dBs setup in dataSource.groovy:
dataSource {
logSql = false
pooled = true
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
and
dataSource_publish {
logSql = false
pooled = true
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:/dbmak/devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE"
}
They both produce files in the project root directory:
devDb.h2.db and dbmak.h2.db
The last thing I did in the dB was to modify the 'sa' password - preferring to set it to a non-null value.
I did this by logging into the dbconsole via user 'sa' and then using the command:
set password 'newPassword'
Which seemed to work fine.
However, when I now try and restart the application in the GGTS I get the error:
org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-173]
I've tried the original null password as well as other login/password combinations that have worked in the past but still get the above error.
One other thing I've done is to replace the h2.db files with recent backed-up copies but still no success. I was wondering if the hibernate system data, containg the 'sa' password, resides elsewhere rather than these individual application databases. If I have a copy of the h2.db files when the system worked I can simply replace it with the modified one that is now failing.
One more thing - when I compare the size of the current (failing - which is 230kb in size) debdb.h2.db file with the backed-up one (which is 1252kb in size) I notice that they are significantly different in size, and when I try and restart the application with the backed-up copy of the db file. After the application fails to start the size goes back to failed size of 230kb.
I have resolved this login issue - as I have two separate Dbs and having set the sa both passwords to a non-null value I have to explicitly define the password for each separate Db.
So, in the DataSource.groovy I now have two sets of login/ password definitions:
dataSource {
username = "sa"
password = "value01"
}
dataSource_publish {
username = "sa"
password = "value02"
}
Without this I believe the login & password is automatically set to 'sa' and "" (i.e: null). And so without the dataSource_publish block on startup the app was attempting, unsuccessfully, to login into the dataSource_publish dB with a null password.
Once you see it it's obvious.

how does get_current_user work

I'm really confused how Google App Engine's User's get_current_user() works. I've looked around the internet at a bunch of different guides and tutorials about login and authentication, and many of them mention similar methods.
If there are a million users logged in to my application at the same time, how can that method possibly work? Does each user get their own instance of the server? How does the server know which client it is talking to?
It doesn't make sense to me at all.
When logging in (by clicking on the URL generated by create_login_url()) a cookie containing user identifying information is prepared and pushed on the client side, then used in subsequent requests until the user logs out or the cookie expires. Calling get_current_user() simply checks the cookie existance/information and responds accordingly.
On the development server the cookie is named dev_appserver_login. I can no longer check the cookie name on GAE as I switched away from the Users API.
The actual handling of the cookie seems to happen somewhere on the Users service backend, for example, by looking at the google/appengine/api/users.py file in the python SDK:
def create_login_url(dest_url=None, _auth_domain=None,
federated_identity=None):
...
req = user_service_pb.CreateLoginURLRequest()
resp = user_service_pb.CreateLoginURLResponse()
try:
apiproxy_stub_map.MakeSyncCall('user', 'CreateLoginURL', req, resp)
...
The end point (at least for the development server) seems to somehow land somewhere in google/appengine/tools/appengine_rpc.py, for example:
#staticmethod
def _CreateDevAppServerCookieData(email, admin):
"""Creates cookie payload data.
Args:
email: The user's email address.
admin: True if the user is an admin; False otherwise.
Returns:
String containing the cookie payload.
"""
if email:
user_id_digest = hashlib.md5(email.lower()).digest()
user_id = "1" + "".join(["%02d" % ord(x) for x in user_id_digest])[:20]
else:
user_id = ""
return "%s:%s:%s" % (email, bool(admin), user_id)
def _DevAppServerAuthenticate(self):
"""Authenticates the user on the dev_appserver."""
credentials = self.auth_function()
value = self._CreateDevAppServerCookieData(credentials[0], True)
self.extra_headers["Cookie"] = ('dev_appserver_login="%s"; Path=/;' % value)

Node-SQL with node.js and MS integrated Security

I have some sample code that is successfully connecting to SQL Server using Microsoft SQL Server user name and password. But I was wondering if there is a way to use integrated security with this script. Basically which means use the logged in user's credentials without supplying a password in the script.
var sql = require('mssql');
var config = {
server: '127.0.0.1',
database: 'master',
user: 'xx',
password: 'xxx',
options : {
trustedConnection : true
}
}
var connection = new sql.Connection(config, function(err) {
// ... error checks
if(err) {
return console.log("Could not connect to sql: ", err);
}
// Query
var request = new sql.Request(connection);
request.query('select * from dbo.spt_monitor (nolock)', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
});
Wish I could add this as a comment but don't have enough reputation yet... but what happens when you run this without providing a username/password in the config object?
Windows Authentication happens at the login level so there is no need to provide it at the application level.
Just browsed the documentation and looks like you cannot provide a raw connection string to connect, but to connect you want to build something that looks like this:
var connectionString= 'Server=MyServer;Database=MyDb;Trusted_Connection=Yes;'
The source code of the mssql module is here: https://github.com/patriksimek/node-mssql/blob/master/src/msnodesql.coffee... maybe you can fork and do a pull request that would provide an optional flag whether to use Windows Authentication or not, and that flag would remove the Uid={#{user}};Pwd={#{password}} (as it's unneeded for Windows Authentication) from the CONNECTION_STRING_PORT variable in the module's source code.

How to properly add OAuth headers for a QuickBooks API call in Google Go

I am just trying to get a proof of concept working to test a connection to the QB api for a QB Online account. I have never tried to make an OAuth connection before like this, so I'm not sure that I am doing it right. Here's what I have so far, and it makes the request but I get a 401 error returned from QB's server (Unauthorized OAuth Token: signature_invalid401SERVER):
client := &http.Client{}
if req, err := http.NewRequest("GET", "https://qbo.intuit.com/qbo1/resource/customers/v2/717594130", nil); err != nil {
//handle error
} else {
req.Header.Add("Authorization", "OAuth oauth_token=\"MY_TOKEN\",oauth_nonce=\"7758caa9-e1f4-4fa1-84c5-5759fd513a88\",oauth_consumer_key=\"MY_KEY\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1369259523\",oauth_version=\"1.0\",oauth_signature=\"MY_SIG\"")
if resp, err := client.Do(req); err != nil {
//handle error
} else {
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
//handle error
}
myOutput := string(contents)
}
}
Could the problem may be with my settings on my QB account instead? There is a setting for "Host Name Domain" that I think it might only allow connections from what I have entered there (which is currently intuit.com). If that is the case, how do I set that to allow connections from my dev app on my localhost?
Are you using the correct OAuth algorithm to generate the signature?
Can you post an actual request/response that shows the outgoing signature/OAuth header, and the response you get back from Intuit?
Your code doesn't show any of that, and it doesn't look like you're using an Intuit DevKit, so that's probably the place to start. My guess would be that the signature you're sending isn't valid. I would highly recommend you find a OAuth library, and use that OAuth library, rather than try to roll your own OAuth algorithm.
As far as this goes:
Could the problem may be with my settings on my QB account instead?
There is a setting for "Host Name Domain" that I think it might only
allow connections from what I have entered there (which is currently
intuit.com).
That is not likely to be the problem... but to get any further than a simple test request, you will need to set that to your host name. If it's a local dev box, you can enter your local dev boxes hostname (e.g. http://localhost/ or http://192.168.1.2/ or anything like that is fine - whatever URL you use to hit your dev box)

GAE Golang - How to properly schedule a Task Queue to a Backend?

There is little information on how to schedule a Task Queue to a Backend in Google App Engine in Go. In TQ's Reference we can read:
// Additional HTTP headers to pass at the task's execution time.
// To schedule the task to be run with an alternate app version
// or backend, set the "Host" header.
Header http.Header
But there is no explanation on what to really set the "Host" to. In Backends' Overview we can similarly read:
Private backends can be accessed by application administrators, instances of the application, and by App Engine APIs and services (such as Task Queue tasks and Cron jobs) without any special configuration.
But again, no explanation is given.
I tried setting the "Host" value to the name of the backend, but the tasks are executed by the normal application.
t := taskqueue.NewPOSTTask("/", map[string][]string{"key": {key}})
t.Header.Add("Host", "backend")
if _, err := taskqueue.Add(c, t, ""); err != nil {
return
}
What is the correct way to schedule a Backend call in GAE Go?
It's easiest to target a backend by using a named queue. e.g.:
_, err = taskqueue.Add(c, &taskqueue.Task{
Path: "/myProcessorPath",
Payload: myPayload,
}, "myQueueName")
Your queue definition specifies the backend. e.g. for myQueueName, you might have a queue.yaml entry that looks like this:
- name: myQueueName
target: myBackendName
rate: 400/s
max_concurrent_requests: 64
bucket_size: 25
retry_parameters:
task_age_limit: 7d
Use the appengine.BackendHostname function to get the hostname for a backend. That should be usable as the Host header for a task.

Resources