Unmanaged code: calling win32 api from .Net

The first and second shots show the happy path. The third shot shows the effect of willfully misspelling MessageBox. You don’t get a compile time error because it is after all unmanaged code that .Net is accessing.

Useful site here

 

using System;
using System.Runtime.InteropServices;
namespace cli01 {
 internal class Program {
enum Options {
 OptionOk = 0,
 OptionOkCancel,
 OptionAbortRetryIgnore,
 OptionYesNoCancel,
 OptionYesNo,
 OptionRetryCancel,
 OptionCancelTryagainContinue
 }
[DllImport("user32.dll")]
 private static extern int MessageBox(IntPtr hWnd, string boxContent, string boxCaption, Options options);
private static void Main() {
 MessageBox(IntPtr.Zero, "The message in the box", "The caption", Options.OptionOkCancel);
 }
 }
}


The MSDN link on MessageBox. Look to be some errors in there suggesting it doesn’t get much love.

Advertisements

SQL Injection: hex and blacklisting

I was given a list of SQL keywords. The idea was that a hacker trying to break the database via a UI or Fiddler/server would be defeated because that (black)list would contain every SQLServer keyword short of ‘select’ (that’s another story). So it would be something like (‘drop’,’delete’,’truncate’) etc. And of course the example assumes that there is no stored procedure with parameters, or ORM, or whilelisting to protect the database. Just effectively plain old unfiltered SQL hitting the database and being allowed to execute dynamic sql, with no parameter binding. So I was being asked to validate the list as being comprehensive.

Well, no blacklist in the world is going to be comprehensive enough, I think. That is because you can obfuscate your intention by passing a hex string as a parameter to e.g.

convert(varchar(max)...

or somesuch. (I guess you could blacklist [convert] etc.)

Anyway, pressing on with my (flawed 🙂 ) evil call…

Suppose you could pass this in your textbox or Fiddler call…

SqlInjection01

Well, you clearly couldn’t say it was harmless… as you just don’t know. In fact this is the result when executed against SQLServer 2014:

SqlInjection02

This is how I built the hex string:

SqlInjection03

, and this is the full picture:

SqlInjection04

 

Sound: loopback recording

I tried code from a number of blogs in an effort to get WASAPI loopback recording working. I only succeeded with one, but that obviously is good enough. The challenge is that WASAPI has a C++ interface. The fundamentals of C++ are simple enough… but when it comes to calling unmanaged code from .Net, I struggle, and need help.

The “winner” then is this person’s Github repository , and specifically his entry on loopback-capture here.

SoundCardCaptureB01

Helpfully the .sln built fine in VS2015.

Executing it after building then consisted of going to the Debug folder. First I naively tried loopback-capture without arguments, which gave me this:

SoundCardCaptureB04.PNG

The “something bad happened” turns out to be a symptom of no active audio playback being detected.
Stepping back, you have a help option:

SoundCardCaptureB05.PNG

Listing devices gives me this:

SoundCardCaptureB06

Running the single found device, with no file name, and making sure you are currently playing audio, results in a default-named  wav file being saved to the current location. The “… spurious glitch… ” below seems to happen regardless. A packet in this context is doubtless a loss I could not even hear, although I have yet to prove that.

SoundCardCaptureB07

SoundCardCaptureB08

QED

 

 

 

Voice recording: fading in and out

For a Musical Interval Training app/ITune I’m working on, I have been trying to get a nice sound when speaking the intervals (e.g. “minor second”). One aspect of making it nice is a fade in and fade out to remove the background hiss before the voice cuts in. I’ve put an example on SoundCloud (see link below – the voice is not mine, as any fule doth know) of the after-sound. It’s recorded using the Roland R-05 mentioned elsewhere here, and the recording is edited using Sony SoundForge 10. SoundForge works fine on Windows 10.

 

JavaScript: Chrome Debugger

I used breakpoints in Chrome for the first time just now. Worth sharing…

I have a sandbox-type html and javascript page when I’m playing, so I always just need to refresh the page in Chrome which I generally keep open.

The plain text is below, but in VS Code, this is how it looks:

test.html

basicstuff.js

So let’s start with a fresh Chrome page…

Go to the location of my page – as you see, there is no html…

Now press F12, which is the short cut for Google Developer Tools. Exactly what you see at this point depends on its most recent state, but let’s say it’s something like this, with the focus on console:

 

 

Click the double chevron, and select sources:

ChromeJs04

 

That brings up your code, both the html and the js. In this I dragged the vertical line to the left to give more real estate:

ChromeJs05

In the next shot, I have already clicked in the margin at line 23, to set a breakpoint. And I am about to bring up the debug controls, in the orange border:

ChromeJs06

ChromeJs07.PNG

If you now press the refresh button to the left of the URL in Chrome, you get this:

ChromeJs08.PNG

There are resume, step into, step over controls just under where you see Security, Audits, above. And hovering over a variable gives you its values, even for an object. In summary, it is REALLY useful, I find.

And finally, pressing F12 again takes you out of debug mode.

<!DOCTYPE html>
 <html>
 <head>
 <title>From the snippets location in Visual Studio Code</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"></link>
 http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js
 http://BasicStuff.js
 </head>
 <body>
</body>
 </html>
 <!-- https://validator.w3.org/nu/#textarea -->
 <!-- Location is [file:///e:/sandbox/javascript/test.html] -->

var clique01 = {
// https://en.wikipedia.org/wiki/Bloomsbury_Group
 type: "luvvies", residence: "London WC1",
 member1: {name: "Virginia Woolf", speciality: "bleakness", category: "novels"},
 member2: {name: "Duncan Grant", speciality: "post-impressionism", category: "art"},
 member3: {name: "John Maynard Keynes", speciality: "spending your way out", category: "economics"},
 member4: {name: "Edward Morgan Forster", speciality: "despair", category: "novels"},
 numMembers: 4
 };
function getNovelists (clique, requiredCategory) {
 var novelists = [];
 var notNovelists = [];
 for (var i = 1; i <= clique.numMembers; i++) {
 var currMemberIndex = "member" + i;
 var currMember = clique[currMemberIndex];
 if (requiredCategory === currMember.category) {
 novelists.push(currMember);
 } else {
 notNovelists.push(currMember);
 }
 delete clique[currMemberIndex];
 }
clique.numMembers -= novelists.length;
 for (var j = 1; j <= clique.numMembers; j++) {
 clique["member"+j] = notNovelists.shift();
 }
return novelists;
 }
var novelists = getNovelists(clique01, "novels");
 var x = novelists;

PowerShell and SQLServer: basic backup and restore

TestDb06

[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Sqlserver.Connectioninfo');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Sqlserver.Management.sdk.sfc');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Sqlserver.SMO');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Sqlserver.SMOExtended');
$srv = New-Object Microsoft.Sqlserver.Management.SMO.Server "(localdb)\MSSQLLocalDB"
$backupFile = "e:\scratch7.bak"
$database = "tempo"
# The backup action...
$backup = New-Object "Microsoft.Sqlserver.Management.SMO.Backup"
$backup.Action = "Database"
$backup.Database = $database
$backup.Devices.AddDevice($backupFile, "File")
$backup.BackupSetDescription = "test desc"
$backup.Incremental = 0
$backup.SqlBackup($srv)
# The restore action...
$restore = new-object Microsoft.SqlServer.Management.Smo.Restore -Property @{
 Action = 'database'
 Database = $database
 ReplaceDatabase = $true
 NoRecovery = $true
}
$device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem -ArgumentList $backupFile,"File"
$restore.Devices.Add($device)
$restore.SqlRestore($srv)

Svg: simple example

<!DOCTYPE html>
<html>
 <head>
 <title>SVG Stuff</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"></link>
 http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js
 </script>
 </head>
 <body>
 <svg height="500" width="500">
 <circle cx="250" cy="250" r="250" fill="hotpink"/>
 </svg>
 </body>
</html>
<!-- https://validator.w3.org/nu/#textarea -->
<!-- Location is [file:///e:/sandbox/javascript/testsvg.html] -->

 

That was how to do it all inline. To decouple the svg from the parent html, you need something like this:

Now, until I included the namespace xmlns=”http://www.w3.org/2000/svg&#8221;, all  got was a dumb broken. With the namespace in place, you get this:

TestSvg05