

Kas Ob.
Members-
Content Count
511 -
Joined
-
Last visited
-
Days Won
9
Kas Ob. last won the day on April 13
Kas Ob. had the most liked content!
Community Reputation
136 ExcellentRecent Profile Visitors
The recent visitors block is disabled and is not being shown to other users.
-
Capture as soon as file paste is selected
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Hi Anders, I want to list some facts 1) Windows Explorer is an application like any other, and it is not essential to the OS itself, so when RDP application run it will interact between two application, hence the need to capture and handle the clipboard, when i copy a file/dir form my own desktop and try to paste it on remote using RDP, then i am pasting the on my application (or RDP), and this should trigger RDP or on the remote to paste, so it should simulate clipboard is filled then send data. 2) CFSTR_TARGETCLSID is irrelevant here as it used internally by Explorer itself. 3) Microsoft RDP does send file in two different ways, one capturing clipboard and its content then simulate on the other hand, well usually it does that, unless Local resources being shared per setting in the RDP connection, this initiate completely different path to share files and synchronize them between host and guest. 4) SHChangeNotifyRegister can capture files changes and many others like copy and paste or rename, initiated by keyboard and/or by mouse. ( might not be useful or needed after all) 5) Th trick is to capture the event then using IShellExplorer to emulate pasting file in the specified directory, (also might be not needed at all) So in short the solution is not to circumvent any thing, not really, because , as example, i built a RDP application, then on the remote part capture the copy event from clipboard (yes using clipboard APIs), then trigger filling the clipboard on my local PC, then on paste on my local i will initiate the sending file after locking the directory same as RDP (this locking will need shell APIs), same can happen in the other way around. Now sounding this loud, i don't understand the need for monitoring the shell operation using SHChangeNotifyRegister ! may be i lost it there or over complicate things, but the copy and paste is happening into different applications, either my remote RDP with the remote Explorer, or local RDP viewer and local Explorer, sending data is handled by the RDP two parts not involving any Explorer. ps: I spent near 3 hours trying to make SHChangeNotification_Lock work, but i think it is working at last ! -
Capture as soon as file paste is selected
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Yes. Yes. In two different way, one when to upload and one to download, but this is somehow irrelevant to your usage, as like Windows RDP it comes baked with special integration with for Windows Explorer aka Windows Shell, these are undocumented API and COM objects. How to do it ? You must understand and use these : 1) IFileOperation https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifileoperation this will capture (and monitor) copying files, moving ,renaming .... 2) IFolderView https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifolderview to find the focused folder in Windows Explorer 3) SHChangeNotifyRegister for hooking shell operation https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shchangenotifyregister 4) IShellWindows https://learn.microsoft.com/en-us/windows/win32/api/exdisp/nn-exdisp-ishellwindows this is the core one to start with and needed to find opened folders ..etc Using these will remove the need for key logger and mouse tracking event, yet in case it failed or and because i can't remember how the hooking was triggered as only reporting or intercepting, meaning you can block, in case that the case and you need to prevent the operation, then you will need key and mouse logger, there is few methods to intercept then cancel if you want. Hope that help, as for all the above, there is many questions on the internet and resources on how to do it, but you specific case need to understand and mix and match an approach. -
First you missing few details about the problem at hand, 1) You are using Client and the client doesn't need a certificate, to be more accurate the default usage for validation on the client side is to check and validate the path of certificate(s) from the server against trusted root or trusted CA. 2) What certificate is on the server, is it valid ? not revoked ? not expired ?.... 3) What is this certificate you mentioned, is it the root or the CA or the end point that server has used to establish the connection ? Now, what you can do or what you should do 1) By default like any TLS connection, the client must have a trusted root store, to resolve the server certificate to, this include any CA in-between them (i mean the end point one aka server and its root), generally either you have a store (punch of certificates) included with in (shipped) your own application, or depend on the OS provided store. 2) Your client doesn't have a store, then it is OK, you can have one root and resolve the path to like above. 3) You are binning the certificate, meaning you will included one certificate, no store, no validation, not best practice at all !, yet it is OK, will work , and fail later ! , but should work (highly not recommended as it is bad and fragile and can render you communication useless any time when the server lose its private key or the certificate leak and you have to replace it...etc), in this exact case and if this is what you are trying to do , then just compare the server certificate against the one in the pem Hope that help, ps: though you had searched the internet, so i will assume you are loading the pem right and you know to validate or compare, but in case you still missing the point and how it should done, then i recommend to use ICS demos, even if you are not going to use that library, but you can study and understand how to validate a certificate ( or try to shoot your self in the foot by comparing against end point only, against all recommendations )
-
Is this VM a developing machine or daily driver for browsing internet and download everything you being offered by an advertisement ? 1) developing machine, then you don't need security scanning for everything all the time, right ? 2) daily driver and testing everything you can download, then leave the defender and install like ten more anti viruses, and make sure to uninstall Delphi for your own security and integrity of your code and generated binaries. It is simple, my developing machine is not allowed to see Internet or access anything outside my home network, i don't download anything suspicious from unknown providers on that machine, heck, i even don't allow Windows to update or to contact Microsoft, so i don't need an virus scanner at all. Anyway, it is up to you keep Windows Defender running or just remove most of this useless scanning each time, in worst case scenario let it scan once, and then disable behavior control and live protection or what ever called, by each AV, also make sure to disable sending samples to laboratories to any AV home, also don't even allow any AV to scan your traffic, this compromise you and your data the most,... i am sure i forgot to mention tens of thing to not do, so the most critical advise of them all think of everything they offer in the settings and use logic, and remember if a malicious code is on your device then it only be detected if it is in the AV database, in other words already known !, so all of this crap of detecting illegal behavior in real time is useless crap, if it is know then cold scan will detect it, if it is unknown then it will run unless real time monitoring is kicking it hence will ask you about everything running on your device, the only good thing from a good scanner if that question happen once only.
-
MsMpEng.exe is Windows Defender scanner and smart locker, and it will repeat the above or similar report for each file or library that bds.exe will load, in that report it is only for one bindcompfmx290.bpl trying to load. So yes disable Defender.
-
Run as admin on unauthorized Windows username
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
Not sure what are you talking about ?! Elevate package and zip file ! You don't need to rerun your process with higher (elevated) privileges, you can elevate or lets say enable a specific privilege for the current process (or token in general, which is most the time is a handle) by using AdjustTokenPrivileges https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges You can use something like this function EnablePrivilege(const PrivilegeName: string): Boolean; var TokenHandle: THandle; NewState: TOKEN_PRIVILEGES; ReturnLength: DWORD; begin Result := False; if OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle) then try NewState.PrivilegeCount := 1; NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; if LookupPrivilegeValue(nil, PChar(PrivilegeName), NewState.Privileges[0].Luid) then begin if AdjustTokenPrivileges(TokenHandle, False, NewState, SizeOf(NewState), nil, ReturnLength) then Result := GetLastError <> ERROR_NOT_ALL_ASSIGNED; end; finally CloseHandle(TokenHandle); end; end; .. const SE_ASSIGN_PRIMARY_TOKEN_NAME = 'SeAssignPrimaryTokenPrivilege'; .. // call it with something like this if EnablePrivilege(SE_ASSIGN_PRIMARY_TOKEN_NAME) then begin .. Just remember to check for elevated process before calling as it will fail, in other words if you are not administrator will not be able to enable SeAssignPrimaryTokenPrivilege hence your process will most likely will be able to run remove process with login etc.. If your account doesn't have TOKEN_ADJUST_PRIVILEGES enabled which is enabled for Administrator ... users then you can't adjust for the current process. Also i said i am not sure if this will solve your problem in full or it will be enough, as there is different causes might prevent such execution, also there is policies should be enabled allowing the such run for a remote process. in all cases run your application or test one, then use Process Explorer, you can see in the Security tab for that application like this screenshot I put a break point using the debugger and confirmed that the SeAssignPrimaryTokenPrivilege privilege is enabled or elevated for this particular privilege, one thing though Process explorer tab need to be closed and reopened to refresh these information. -
Run as admin on unauthorized Windows username
Kas Ob. replied to Mustafa E. Korkmaz's topic in Windows API
As Francois pointed, your user itself doesn't privilege to execute such operation, which is in this case CreateProcess(xx) with different token on different station, not %100 sure but i think your user should be have SeAssignPrimaryTokenPrivilege https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/user-rights-assignment https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/replace-a-process-level-token -
Please, pretty please, make it [0..63] not [0..64], it is triggering my OCD ! Also having goosebumps from that off by one to an odd number !
-
Overflow Checking from 10.4 onwards
Kas Ob. replied to pmcgee's topic in RTL and Delphi Object Pascal
I think 48 was there and the code changed and that comment along that excerpt stayed, Anyhow, the random generation algorithm is LCG, and it is fast and enough for general purposes, it is like PCG https://en.wikipedia.org/wiki/Permuted_congruential_generator , also there is many others, they are fast, extremely fast but they are not cryptographically secure, what does that means ? It means if i get hold on few (or lot, it depends) of the output random of that algorithm then i can predict the exact state (seed) at that moment, hence i can predict all the future random output. Why this is critically insecure ? I will give an example, in TLS connection key are randomly generated (private keys), while only public key are sent over the wire and they can NOT compromise the private key but there is different things in the SSL/TLS header that can help break the private key, if the software is using weak random generator like LCG then it also will be used in the sessionID and in the IV and nonces ..etc that are plainly sent in the TLS header for the handshake, hence if the attacker predicted the state then it at least he can just produce random numbers and all your private keys (future ones) are exposed. LCG is fins for general big numbers library but it can not be used with PKI and any cryptographic library/implementation, as you are using RSA, then for your own learning it is fine, but do not trust its random or key coming form it. ps : in the mentioned library LCG is defined as form here https://en.wikipedia.org/wiki/Permuted_congruential_generator and constants are a,c and m , you can see them here https://github.com/rvelthuis/DelphiBigNumbers/blob/master/Source/Velthuis.RandomNumbers.pas#L116C1-L136C5 m is a little not so obvious but it is in the bit shift meaning m=64-Bits rendering, with this known and as Bits is used in Next which called with three variant 31,32 and 64, all this values just render it more predictable, at 32 all you need is somethign around 32 byte to calculate the state (seed) ! also SessionID in TLS is 32byte ! meaning with the wrong PRNG it is enough to predict the exact state and predict the all exact private keys, breaking the secure connection alltogether. Also 48 bits (the comment) it should reflect on 64-Bits (or Bits) being 48, but i don't see that anywhere, may it was there in the past. -
I believe the needed buffer is 56 (2*28) for IPv6 so [0..55] bytes should be enough, if i am not missing something.
-
I forgot to mention important thing about that structure and its size. You can't and must not put it on the stack !, it will overflow and destroy/corrupt the stack, so it must be on the heap and must be zeroed before usage as best practice, because there is two addresses (pointing to two structures) will be filled by that API and it will put them right after the initial structure and fix the addresses.
-
Here a fully working example, modified from a code for different thing, yet it shows successful use of SO_BSP_STATE unit uReadSocketInfo; interface uses Windows, Winsock2; function WSAInitialize(MajorVersion, MinorVerion: Integer): Boolean; function WSADeInitialize: Boolean; function CheckTCPPortNB(const IP: string; Port: Integer; out TimeMS: Integer): Boolean; var CHECKPOINT_TIMEOUT_MS: integer = 1000; implementation procedure GetSocketInformation(s: TSocket); var pSockAddresssI: PCSADDR_INFO; Res, WsaLError, OptLen: Integer; begin OptLen := SizeOf(CSADDR_INFO) + 128; // yes the original size is 24, but more is needed and will fail on 24 // for IPv4 an extra of 32 bytes is enough instead of 128 pSockAddresssI := GetMemory(OptLen); try Res := getsockopt(s, SOL_SOCKET, SO_BSP_STATE, PAnsiChar(pSockAddresssI), OptLen); if Res = SOCKET_ERROR then WsaLError := WSAGetLastError else Writeln('Socket information :'); finally FreeMemory(pSockAddresssI); end; end; function CheckTCPPortNB(const IP: string; Port: Integer; out TimeMS: Integer): Boolean; var s: TSocket; Addr: TSockAddrIn; SAddr: TSockAddr absolute Addr; QPF, QPC1: Int64; NonBlockMode: DWORD; Res: Integer; FDW, FDE: fd_set; TimeVal: TTimeVal; function GetElapsedTime: Integer; var QPC2: Int64; begin QueryPerformanceCounter(QPC2); Result := (QPC2 - QPC1) div (QPF div 1000); end; begin Result := False; TimeMS := 0; s := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if s = INVALID_SOCKET then Exit; NonBlockMode := 1; ioctlsocket(s, Integer(FIONBIO), NonBlockMode); Addr.sin_family := AF_INET; Addr.sin_addr.S_addr := inet_addr(PAnsiChar(AnsiString(IP))); Addr.sin_port := htons(Port); QueryPerformanceFrequency(QPF); QueryPerformanceCounter(QPC1); Res := connect(s, SAddr, SizeOf(SAddr)); if (Res = SOCKET_ERROR) and (WSAGetLastError = WSAEWOULDBLOCK) then begin TimeVal.tv_sec := 0; // 1 sec = 1000000 usec TimeVal.tv_usec := 1000; // 1 ms = 1000 usec repeat FDW.fd_count := 1; FDW.fd_array[0] := s; FDE.fd_count := 1; FDE.fd_array[0] := s; TimeMS := GetElapsedTime; Res := select(1, nil, @FDW, @FDE, @TimeVal); until (Res > 0) or (TimeMS >= CHECKPOINT_TIMEOUT_MS); end; Result := (FDW.fd_count = 1) and (FDE.fd_count = 0); /// we have connected socket with full valid information if Result then begin GetSocketInformation(s); end; /// TimeMS := GetElapsedTime; if s <> INVALID_SOCKET then closesocket(s); end; function WSAInitialize(MajorVersion, MinorVerion: Integer): Boolean; var WSA: TWsaData; begin Result := WSAStartup(MakeWord(MajorVersion, MinorVerion), WSA) = 0; if Result then begin Result := (Byte(WSA.wVersion shr 8) = MinorVerion) and (Byte(WSA.wVersion) = MajorVersion); if not Result then begin Result := False; WSADeInitialize; end; end; end; function WSADeInitialize: Boolean; begin Result := WSACleanup = 0; end; initialization WSAInitialize(2, 2); finalization //WSADeInitialize; end. a small project to use it program SocketInformation; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, uReadSocketInfo in 'uReadSocketInfo.pas'; var Time : Integer; begin try CheckTCPPortNB('142.251.36.46', 80, Time); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Readln; end. Put a break point with debugger on the getsockopt and you will get 32 bytes additional bytes (on top the 24 bytes, the structure size) is needed for IPv4 so i suspect more is needed for IPv6, this is undocumented behavior.
-
Overflow Checking from 10.4 onwards
Kas Ob. replied to pmcgee's topic in RTL and Delphi Object Pascal
Literally the definition of Karatsuba, to split in half and perform on half length thus reducing the complexity of time needed not the complexity of the implementation, in case of 64bit then only two half is needed with no recursion, Wikipedia page explain it, but there is simpler resources on the Internet to explain it. Fun fact : There is also an algorithm named Toom-Cook https://en.wikipedia.org/wiki/Toom–Cook_multiplication reduce the multiplication further but increase the complexity of implementation more, both algorithm shift the operation into smaller part reducing the need for multiplication carry but increase the addition operation with its carry. Just common knowledge to whom may be interested. Yes it is simple, but if you want the most beautiful mathematically algorithm (i see it like that), is El-Gamal (sometimes written (ElGamal), and once you built your RSA you will find implementing ElGamal is relatively close and not any more a complex task, as you will need the little different or adjusted arithmetic, i mean you will have primality test along with GCD (GCD might be needed but that depend on your approach or method), ElGamal has a feature which can be used with Elliptic Curve and their finite fields hence decreasing the length of the keys substantially, so it might interest you and your friends ! https://en.wikipedia.org/wiki/ElGamal_encryption https://en.wikipedia.org/wiki/ElGamal_signature_scheme A little more detailed resources https://www.geeksforgeeks.org/elgamal-encryption-algorithm/ https://compare-encryption-algorithms.mojoauth.com/rsa-4096-vs-elgamal-variable-key-size/ Yup, nothing beats Miller–Rabin test in speed, it looks nice book. Focus on RSA !, ElGamal will need different beast https://en.wikipedia.org/wiki/Modular_exponentiation but after RSA you will find it easy as it is pretty straight forward as listed in Wikipedia. Again good luck. -
Overflow Checking from 10.4 onwards
Kas Ob. replied to pmcgee's topic in RTL and Delphi Object Pascal
I don't have any of the mentioned above IDEs, but i see a problem or two .. well more than that a lot, but will talk about your exact problem first 1) The directives are wrong and mixed, and here how they should look like function TRandom.Next(Bits: Integer): UInt32; begin {$IFOPT R+} {$DEFINE HasRangeChecks} {$ENDIF} {$IFOPT Q+} {$DEFINE HasOverflowChecks} {$ENDIF} {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} FSeed := (FSeed * CMultiplier + CIncrement); Result := UInt32(FSeed shr (64 - Bits)); // Use the highest bits; Lower bits have lower period. {$IFDEF HasRangeChecks} {$RANGECHECKS ON} {$ENDIF} {$IFDEF HasOverflowChecks} {$OVERFLOWCHECKS ON} {$ENDIF} end; Because we have two overflow check can be triggered here, not one !, Integer overflow range overflow come from multiplication and form truncation while mixing signed and unsigned, both need to be disabled, also the R+ for the range while wrongly was Q. 2) I tried this small test procedure RunTest; var Rand: IRandom; A, B, C: BigInteger; begin Rand := TRandom.Create($FF00FE01FD02FC03); // sooner ! Trigger overflow check at TRandomBase.NextBytes //Rand := TRandom.Create($FF00FF01FF02FF03); // Trigger overflow check at TRandom.Next A.Create(1024, Rand); B.Create(1024, Rand); C := A * C; Writeln('A = ' + A.ToHexString); Writeln('B = ' + B.ToHexString); Writeln('C = ' + C.ToHexString); end; And we have another place that has an overflow, but the fix is easy (again sign bit!!) procedure TRandomBase.NextBytes(var Bytes: array of Byte); var Head, Tail: Integer; N, {Rnd,} I: Integer; Rnd : UInt32; // <--- fix overflow begin Didn't go through more tests or any deeper in digging into the source. Now to the other problems 3) This pseudorandom number generator is not cryptographically secure , it has very small duration and depend on single modular operation which is 2^(64-Bits)= 2^k, this can't be considered secure it is as predictable as it can be by design, but choosing 2^k make brute force algorithm for it way much faster ! 4) I don't understand from where the assumption of only 48 bits are only used, this is strange and out of the context or this family of PRNG, may be i missed something with Bits, but will not dig deeper in it. 5) the core problem is depending on Int64, this is signed and by using signed we lose a bit and confuse the compiler and math, while gains nothing in return, this family of PRNG which call LCG https://en.wikipedia.org/wiki/Linear_congruential_generator doesn't handle signed numbers, and doesn't need as it is by definition, so using Int64 should be replaced with UInt64 for the constants, and the algorithm too. 6) tried to figure out this code You are going with Karatsuba https://en.wikipedia.org/wiki/Karatsuba_algorithm , nice it is the right way when you are in the corner, also much cleaner for limbs, yet the last masking is again wrong assuming (you are following the original code) it can or should be signed operation, this should be changed to unsigned, and return the sign bit to the fold, as it is by design is using the highest 32 bit, by losing the sign, where entropy is lost, we left with 31 bit randomness. About learning and implementing RSA, yes do it and you will learn much, and i wish you good luck, also a suggestion : why not read more about CSPRNG and implement one ,a cryptographically secure (CS) one, there is one i liked very much due it speed and portability, it is based on CHAHCA with reduced rounds called ChaCha8, it use the same permutation as ChaCha20 but with 8 rounds, it is secure and small as it can be, and used in Go Lang applications extensively, anyway it is not so important and most important thing is understanding is that security is like a chain and the chain is weak as its weakest link, randomness is always the most crucial link that when break (insecure) it will render everything built on it insecure, and last suggestion if you are going to use you own implementation of RSA in production for clients then test it then test it and test it again and think a lot before using your own implementation, it is not recommended by anyone ( as i think you read again and again, things like don't implement your own...), but you should learn it inside out, so go with it. -
executing a command with ssh-pascal runs into timeout
Kas Ob. replied to dummzeuch's topic in Network, Cloud and Web
I am intrigued here !, And really want to ask this , Did you asked any AI for solution ? Because the solution is very simple unless there is something missing or the ssh library is broken, it could be broken on both client and server, but what concern me is what server SSH is being used, and few numbers will be great to understand this. Anyway, my first suggestion is to hack your way into it, well it is a workaround to guarantee the TCP socket connection is alive and being pinged, just add another channel for port forwarding if that is allowed on server side, this should solve your problem and enforce ping for that channel on that socket to be communicated hence stopping the timeout, well unless the timeout is coming from different cause and has nothing to do with SSH per se. Also what are the setting on server for keepalive interval and max count ?