How to encrypt post parameters in Inno Setup - encryption

I have to post some user entered dynamic data to my server while installing. I can post the data successfully. But to post the data securely i have to encrypt the data while posting. I don't know how to do this..
Here is my code,
procedure CurStepChanged(CurStep: TSetupStep);
var
WinHttpReq: Variant;
begin
if CurStep = ssInstall then
begin
if AutoCheckRadioButton.Checked = True then
begin
WinHttpReq := CreateOleObject('WinHttp.WinHttpRequest.5.1');
WinHttpReq.Open('POST', '<web_server>', false);
WinHttpReq.SetRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
WinHttpReq.Send('<need to encrypt data>');
{ WinHttpReq.ResponseText will hold the server response }
end;
end;
end;
Thanks in advance for your help

Just use an HTTPS URL, like:
https://www.example.com/
The encryption happens automatically.

Related

How can I generate a url to a new AppInsights query?

I have a process that generates AppInsights telemetry. I would like to prove a link to a query in AppInsights. However, it is not the same query every time - the parameters change. I know I can share a link to an existing query, but how do I generate such a link to a new query?
In your Application Insights Query Editor, we have an option called Copy link to query. In this link we have following details:
The URL generated from this action has the following format:
https://portal.azure.com/## TENANT_ID/blade/Microsoft_Azure_Monitoring_Logs/LogsBlade/resourceId/%2Fsubscriptions%2F SUBSCRIPTION_ID %2FresourceGroups%2F< RESOURCEGROUP%2Fproviders%2Fmicrosoft.insights%2Fcomponents%2F APPLICATION INSIGHTS_INSTANCE_NAME /source/LogsBlade.AnalyticsShareLinkToQuery/q/ ENCODED
BASE 64_KQL_QUERY /timespan/TIMESPAN
I’ve emphasized in bold here the parameters of the URL. These parameters have the following values:
TENANT_ID: Your Tenant ID
SUBSCRIPTION_ID: Your Azure Subscription ID that contains the Application Insights instance.
RESOURCE_GROUP: Your Resource Group where the Application Insights instance is deployed.
APPINSIGHTS_INSTANCE_NAME: Your Application Insights instance Name.
ENCODED_KQL_QUERY: Base64 encoding of your query text zipped and URL encoded
TIMESPAN: time filter for the query (optional).
If your query has less than 1600 characters, you can also replace the q parameter in the above URL with a query parameter, and the encoded string will simply be your query plain text escaped (without zipping and encoding).
Dynamic URL it’s important to:
Take the text of your KQL query
Zip it
Encode it in Base64
A C# code that does the encoding of the KQL query is the following:
Generate the Query whatever you want and pass that into the below function to get the Encoded base 64 URL and you can add this in a base URL of application insights.
static string Encodedbase64KQLQuery(string query)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(query);
using (MemoryStream memoryStream = new MemoryStream())
{
using (GZipStream compressedStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
{
compressedStream.Write(bytes, 0, bytes.Length);
}
memoryStream.Seek(0, SeekOrigin.Begin);
Byte[] bytedata = memoryStream.ToArray();
string encodedBase64Query = Convert.ToBase64String(bytedata);
return HttpUtility.UrlEncode(encodedBase64Query);
}
}
Please visit this blog which helped me a lot.
Thanks Delliganesh and Stefano from the blog link. Here is a simple JavaScript example. Be sure to replace all 4 constant values at top and the sessionId when calling the function. You can also tweak the query, but just keep in mind the 1600 character limit as described above and in the blog.
const APP_INSIGHTS_INSTANCE_NAME = "APP_INSIGHTS_INSTANCE_NAME";
const APP_INSIGHTS_RESOURCE_GROUP = "APP_INSIGHTS_RESOURCE_GROUP";
const APP_INSIGHTS_SUBSCRIPTION_ID = "APP_INSIGHTS_SUBSCRIPTION_ID";
const APP_INSIGHTS_TENANT_ID = "APP_INSIGHTS_TENANT_ID";
const getAppInsightsQueryUrl = ({ sessionId }) => {
const query = `requests | where session_Id == "${sessionId}"`;
const url = `https://portal.azure.com/##${APP_INSIGHTS_TENANT_ID}/blade/Microsoft_Azure_Monitoring_Logs/LogsBlade/resourceId/%2Fsubscriptions%2F${APP_INSIGHTS_SUBSCRIPTION_ID}%2FresourceGroups%2F${APP_INSIGHTS_RESOURCE_GROUP}%2Fproviders%2Fmicrosoft.insights%2Fcomponents%2F${APP_INSIGHTS_INSTANCE_NAME}/source/LogsBlade.AnalyticsShareLinkToQuery/query/${encodeURI(
query
)}/timespan/TIMESPAN`;
return url;
};
getAppInsightsQueryUrl({
sessionId: 'my-session-id',
})

GO API with SQLITE3 can't DELETE tuple from db

Hello fellow developers.
I am trying to learn GO while constructing a simple web API using sqlite3. I got stuck at somepoint where i am unable to delete rows from my table by sending a DELETE request from postman. I am trying to use the code below to delete a row. I have already verified that I have access to db and I can also delete rows by using command tool of sqlite3. I do not understand what is wrong!
func deleteArticle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // get any params
db := connectToDB(dbName)
defer db.Close()
_, err := db.Query("DELETE FROM article WHERE id=" + params["id"])
if err != nil {
fmt.Fprintf(w, "article couldn't be found in db")
}
}
Here is the navigation part:
myRouter.HandleFunc("/articles/{id}", deleteArticle).Methods("DELETE")
No mather what I do I cannot delete an article from db using postman.
Thanks bunches.
Thanks to #mkopriva 's comments I have learned that
1.
It is very important that you do not use Query nor QueryRow for SQL
queries that do not return any rows, for these cases use the Exec
method. When you use Query you always have to assign the result to a
non-blank identifier, i.e. anything but _, and then invoke the Close
method on that once you're done with the result. If you do not do that
then your application will leak db connections and very soon will
start crashing.
2.
when you want to pass user input (including record ids) to your
queries you have to utilize, at all times, the parameter-reference
syntax supported by the sql dialect and/or dirver you are using, and
then pass the input separately. That means that you should never do
Exec("DELETE FROM article WHERE id=" + params["id"]),
instead you should always do
Exec("DELETE FROM article WHERE id= ?",params["id"])
If you do not do it the proper way and instead continue
using plain string concatenation your app will be vulnerable to SQL
injection attacks.
Regarding this information I have changed my code into:
func deleteArticle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // get any params
db := connectToDB(dbName)
defer db.Close()
fmt.Printf("%q\n", params["id"])
statement, err := db.Prepare("DELETE FROM article WHERE id= ?")
if err != nil {
fmt.Fprintf(w, "article couldn't be found in db")
}
statement.Exec(params["id"])
}
Which has solved my problem. So thank you #mkopriva

Parse a url with # in GO

So I'm receiving a request to my server that looks a little something like this
http://localhost:8080/#access_token=tokenhere&scope=scopeshere
and I can't seem to find a way to parse the token from the url.
If the # were a ? I could just parse it a standard query param.
I tried to just getting everything after the / and even the full URL, but with no luck.
Any help is greatly appreciated.
edit:
So I've solved the issue now, and the correct answer is you can't really do it in GO. So I made a simple package that will do it on the browser side and then send the token back to the server.
Check it out if you're trying to do local twitch API stuff in GO:
https://github.com/SimplySerenity/twitchOAuth
Anchor part is not even (generally) sent by a client to the server.
Eg, browsers don't send it.
For parse urls use the golang net/url package: https://golang.org/pkg/net/url/
OBS: You should use the Authorization header for send auth tokens.
Example code with extracted data from your example url:
package main
import (
"fmt"
"net"
"net/url"
)
func main() {
// Your url with hash
s := "http://localhost:8080/#access_token=tokenhere&scope=scopeshere"
// Parse the URL and ensure there are no errors.
u, err := url.Parse(s)
if err != nil {
panic(err)
}
// ---> here is where you will get the url hash #
fmt.Println(u.Fragment)
fragments, _ := url.ParseQuery(u.Fragment)
fmt.Println("Fragments:", fragments)
if fragments["access_token"] != nil {
fmt.Println("Access token:", fragments["access_token"][0])
} else {
fmt.Println("Access token not found")
}
// ---> Others data get from URL:
fmt.Println("\n\nOther data:\n")
// Accessing the scheme is straightforward.
fmt.Println("Scheme:", u.Scheme)
// The `Host` contains both the hostname and the port,
// if present. Use `SplitHostPort` to extract them.
fmt.Println("Host:", u.Host)
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println("Host without port:", host)
fmt.Println("Port:",port)
// To get query params in a string of `k=v` format,
// use `RawQuery`. You can also parse query params
// into a map. The parsed query param maps are from
// strings to slices of strings, so index into `[0]`
// if you only want the first value.
fmt.Println("Raw query:", u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
}
// part of this code was get from: https://gobyexample.com/url-parsing

SQLiteException: near "If": syntax error

I am converting a 'SQL Server 2008' stored procedure to 'SQLite'.
But facing problem with the following query:
If (Select Count(UserId) From Users Where RememberMe = 'True') > 1
Update Users Set RememberMe = 'False'
Select UserName From Users Where RememberMe = 'True'
While executing the above query in the 'SQLite Administrator' or 'SQLite Expert', I am getting the following error message:
Error occured: near "If": syntax error
I am a beginner in SQLite.
Please guide me.
Thanks & Regards,
Sqlite does not support if. You can use CASE instead of it.
SQLite doesn't support stored procedures.
But it looks like your code only updates the Users table to set RememberMe = 'False' for users that had it set to 'True'. If this is the case, then you don't need to do the If part at all. This should suffice:
UPDATE Users SET RememberMe = 'False' WHERE RememberMe = 'True';

How to get the current logged on user, including domain in Delphi 2009?

I need to get the current logged on username? I need this to work properly when I call the code from ASP.NET which is working in Windows Authentication mode. i.e. I do not want to get the ASPNET user in that circumstance, but the impersonated user. This is related to my earlier question. Everything I try returns ASPNET.
In your other question you wrote that you configured ASP.NET to use Windows authentication with impersonation:
<system.web>
...
<authentication mode="Windows"/>
<identity impersonate="true"/>
...
</system.web>
Does the ASP.NET application show the correct credentials (user and domain)?
Are you invoking the Delphi function using the correct Identity context, like
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
try
{
ctx = winId.Impersonate();
// call Delphi function, passing the identity context
}
catch
{
}
finally
{
if (ctx != null)
ctx.Undo();
}
Update:
If the COM abject is called from the code behind for a web form page, you can try to set ASPCOMPAT property of the web form page to true.
See:
http://dotnetdebug.net/2006/06/13/aspnet-web-application-and-sta-com-objects-security-issues/
The "identity" tag makes sure that the
thread executing the request (the MTA
thread) will impersonate its security
context to the user specified in the
tag but our STA COM object
eventually was created on the default
STA thread which was not impersonate,
causing it to get the security context
of the process (which was IUSR_XXX –
the least powerful user of all).
Perhaps your IADsWinNTSystemInfo approach (from the linked previous question) returns current process' account information, but ASP.NET is impersonating on a thread level?
Try this:
type
PTokenUser = ^TTokenUser;
TTokenUser = packed record
User: SID_AND_ATTRIBUTES;
end;
function GetCurrentUserName(out DomainName, UserName: string): Boolean;
var
Token: THandle;
InfoSize, UserNameSize, DomainNameSize: Cardinal;
User: PTokenUser;
Use: SID_NAME_USE;
_DomainName, _UserName: array[0..255] of Char;
begin
Result := False;
DomainName := '';
UserName := '';
Token := 0;
if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, Token) then
begin
if GetLastError = ERROR_NO_TOKEN then // current thread is not impersonating, try process token
begin
if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token) then
Exit;
end
else
Exit;
end;
try
GetTokenInformation(Token, TokenUser, nil, 0, InfoSize);
User := AllocMem(InfoSize * 2);
try
if GetTokenInformation(Token, TokenUser, User, InfoSize * 2, InfoSize) then
begin
DomainNameSize := SizeOf(_DomainName);
UserNameSize := SizeOf(_UserName);
Result := LookupAccountSid(nil, User^.User.Sid, _UserName, UserNameSize, _DomainName, DomainNameSize, Use);
if Result then
begin
SetString(DomainName, _DomainName, StrLen(_DomainName));
SetString(UserName, _UserName, StrLen(_UserName));
end;
end;
finally
FreeMem(User);
end;
finally
CloseHandle(Token);
end;
end;
Example usage:
var
DomainName, UserName: string;
begin
if not GetCurrentUserName(DomainName, UserName) then
RaiseLastOSError;
Writeln(Format('%s\%s', [DomainName, UserName]));
end;
Hope this helps.
This is a part of the code of my LoadProfile tool, it works well in Delphi 2010:
const
UNLEN = 256; // Maximum user name length
var
TokenHandle: THandle; // Handle to the Processes' Acces Token
cbTokenInfo: DWORD; // Size of TokenInfo in Bytes
pTokenUser: PTOKEN_USER; // Pointer to a TOKEN_USER record
cchName: DWORD; // Count of characters (length) of the Username array
cchDomain: DWORD; // Count of characters (length) of the Domainname array
peUse: DWORD; // Account type for LookupAccountSid
UserName: array[0..UNLEN] of Char; // Holds the Username
DomainName: array[0..UNLEN] of Char; // Holds the Domainname
ComputerName: array[0..UNLEN] of Char; // Hold the Computername
// Open the Current Process' Token
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY or
TOKEN_IMPERSONATE or TOKEN_DUPLICATE, TokenHandle);
// Check if we have a valid handle
if TokenHandle = 0 then
Exit;
{ We will use GetTokenInformation to get the user's SID, the first call
to GetTokenInformation is used to determine how much memory we need to
allocate }
GetTokenInformation(TokenHandle, TokenUser, nil, 0, cbTokenInfo);
// as documented the call should fail with ERROR_INSUFFICIENT_BUFFER
if (GetLastError() <> ERROR_INSUFFICIENT_BUFFER) then
Exit;
// Allocate Memory
pTokenUser := HeapAlloc(GetProcessHeap(), 0, cbTokenInfo);
if (pTokenUser = nil) then
Exit;
// Retrieve the user information from the token.
if ( not GetTokenInformation(TokenHandle, TokenUser, pTokenUser,
cbTokenInfo, cbTokenInfo)) then
Exit;
cchName := Length(UserName);
cchDomain := Length(DomainName);
peUse:= SidTypeUser;
// Use the SID to find User and Domain Name
Write('LookupAccountSid... ');
if not LookupAccountSid(nil, pTokenUser^.User.Sid, UserName, cchName,
DomainName, cchDomain, peUse) then
Exit;
// Cleanup
if (pTokenUser <> nil) then
HeapFree(GetProcessHeap(), 0, pTokenUser);
WriteLn('CloseHandle... OK');
CloseHandle(TokenHandle);

Resources