-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinSCP-old.php
More file actions
302 lines (241 loc) · 9.86 KB
/
WinSCP-old.php
File metadata and controls
302 lines (241 loc) · 9.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
class WinSCP {
// WinSCP password constants
const PW_MAGIC = 163; // 0xA3
const PW_FLAG = 255; // 0xFF
const PW_INTERNAL = 0x00;
const PW_MAXLEN = 48;
const PW_STRING = '0123456789ABCDEF';
private static $chars = [];
/**
* Convert JSON to WinSCP INI format
*/
public static function jsonToIni($jsonFile, $outputFile = null) {
$data = json_decode(file_get_contents($jsonFile), true);
$content = "";
foreach ($data['sessions'] as $session) {
$content .= self::processSession($session, "");
}
if ($outputFile) {
file_put_contents($outputFile, $content);
return $outputFile;
}
return $content;
}
/**
* Convert WinSCP INI to JSON format
*/
public static function iniToJson($iniFile, $outputFile = null) {
$ini = parse_ini_file($iniFile, true, INI_SCANNER_RAW);
$sessions = [];
foreach ($ini as $key => $value) {
if (strpos($key, 'Sessions\\') === 0 && isset($value['HostName'])) {
$sessionName = substr($key, 9); // Remove 'Sessions\'
$session = self::parseSession($sessionName, $value);
$sessions[] = $session;
}
}
$result = ['sessions' => $sessions];
if ($outputFile) {
file_put_contents($outputFile, json_encode($result, JSON_PRETTY_PRINT));
return $outputFile;
}
return $result;
}
/**
* Process session recursively
*/
private static function processSession($item, $path) {
$content = "";
// If this item has hostname, it's a host entry
if (isset($item['hostname'])) {
$name = $item['name'] ?? ($item['username'] . '@' . $item['hostname']);
$fullPath = $path ? $path . '/' . $name : $name;
$content .= "[Sessions\\$fullPath]\n";
$content .= "HostName=" . $item['hostname'] . "\n";
if (isset($item['port']) && $item['port'] != 22) {
$content .= "PortNumber=" . $item['port'] . "\n";
}
$content .= "UserName=" . $item['username'] . "\n";
// Use proper WinSCP encryption
if (isset($item['password'])) {
$encryptedPassword = self::encrypt($item['username'], $item['hostname'], $item['password']);
$content .= "Password=" . $encryptedPassword . "\n";
}
$content .= "\n";
}
// If this item has category, add it to path
if (isset($item['category'])) {
$newPath = $path ? $path . '/' . $item['category'] : $item['category'];
// Process hosts in this category
if (isset($item['hosts'])) {
foreach ($item['hosts'] as $host) {
$content .= self::processSession($host, $newPath);
}
}
// Process subcategories
if (isset($item['subcategories'])) {
foreach ($item['subcategories'] as $subcategory) {
$content .= self::processSession($subcategory, $newPath);
}
}
}
return $content;
}
/**
* Parse session from INI format
*/
private static function parseSession($sessionPath, $data) {
$pathParts = explode('/', $sessionPath);
$session = [
'name' => end($pathParts),
'path' => $sessionPath,
'hostname' => $data['HostName'],
'port' => isset($data['PortNumber']) ? (int)$data['PortNumber'] : 22,
'username' => $data['UserName']
];
// Handle both PasswordPlain and encrypted Password
if (isset($data['PasswordPlain'])) {
$session['password'] = $data['PasswordPlain'];
} elseif (isset($data['Password'])) {
$session['password_encrypted'] = $data['Password'];
$session['password'] = self::decrypt($data['UserName'], $data['HostName'], $data['Password']);
}
return $session;
}
/**
* Generate random number between min and max
*/
private static function rand($min, $max) {
return mt_rand($min, $max);
}
/**
* Encrypt a single character (WinSCP algorithm)
*/
private static function simpleEncryptChar($char) {
$char = (~$char ^ self::PW_MAGIC) & 0xFF;
$a = ($char & 0xF0) >> 4;
$b = ($char & 0x0F) >> 0;
return self::PW_STRING[$a] . self::PW_STRING[$b];
}
/**
* Decrypt next character (based on working other/winscp.php)
*/
private static function decNextChar(&$passbytes) {
if (empty($passbytes)) {
return array('val' => 0, 'passbytes' => $passbytes);
}
$a = array_shift($passbytes);
$b = array_shift($passbytes);
$val = (~((($a << 4) + $b) ^ self::PW_MAGIC)) & self::PW_FLAG;
return array('val' => $val, 'passbytes' => $passbytes);
}
/**
* Encrypt password using EXACT WinSCP algorithm (based on Python code)
* Structure: [length][shift][shift_padding][username+hostname+password][final_padding]
*/
public static function encrypt($username, $hostname, $password) {
// Python algorithm: password = key + password where key = username + hostname
$fullPassword = $username . $hostname . $password;
$result = [];
// Calculate shift (random padding before the actual data)
$shift = 0;
if (strlen($fullPassword) < self::PW_MAXLEN) {
$shift = self::rand(0, self::PW_MAXLEN - strlen($fullPassword));
}
// 1. First byte: length of the full password string
$result[] = self::simpleEncryptChar(strlen($fullPassword));
// 2. Second byte: shift value (how many random bytes to skip)
$result[] = self::simpleEncryptChar($shift);
// 3. Add shift bytes of random padding
for ($i = 0; $i < $shift; $i++) {
$result[] = self::simpleEncryptChar(self::rand(0, 255));
}
// 4. Add the actual password data
for ($i = 0; $i < strlen($fullPassword); $i++) {
$result[] = self::simpleEncryptChar(ord($fullPassword[$i]));
}
// 5. Pad to exactly 48 bytes (96 hex chars)
while (count($result) < self::PW_MAXLEN) {
$result[] = self::simpleEncryptChar(self::rand(0, 255));
}
return 'A35C' . implode('', $result);
}
/**
* Recreate EXACT encryption by reverse engineering the shift and padding
*/
public static function recreateExact($username, $hostname, $password, $targetEncrypted) {
// Remove A35C prefix
$target = substr($targetEncrypted, 4);
$fullPassword = $username . $hostname . $password;
// Convert target to bytes
$targetBytes = [];
for ($i = 0; $i < strlen($target); $i += 2) {
$hex = substr($target, $i, 2);
$a = hexdec($hex[0]);
$b = hexdec($hex[1]);
$val = 0xFF & ~((($a << 4) + $b) ^ 0xA3);
$targetBytes[] = $val;
}
// Extract the exact shift value (2nd byte)
$exactShift = $targetBytes[1];
// Extract the exact padding values
$exactShiftPadding = array_slice($targetBytes, 2, $exactShift);
$exactFinalPadding = array_slice($targetBytes, 2 + $exactShift + strlen($fullPassword));
// Recreate with exact values
$result = [];
// 1. Length
$result[] = self::simpleEncryptChar(strlen($fullPassword));
// 2. Exact shift
$result[] = self::simpleEncryptChar($exactShift);
// 3. Exact shift padding
foreach ($exactShiftPadding as $padByte) {
$result[] = self::simpleEncryptChar($padByte);
}
// 4. Password data
for ($i = 0; $i < strlen($fullPassword); $i++) {
$result[] = self::simpleEncryptChar(ord($fullPassword[$i]));
}
// 5. Exact final padding
foreach ($exactFinalPadding as $padByte) {
$result[] = self::simpleEncryptChar($padByte);
}
return 'A35C' . implode('', $result);
}
/**
* Decrypt WinSCP password (handles the correct structure)
*/
public static function decrypt($username, $hostname, $encrypted) {
// Remove A35C prefix if present
if (strpos($encrypted, 'A35C') === 0) {
$encrypted = substr($encrypted, 4);
}
$key = $username . $hostname;
$passbytes = array();
// Convert hex string to decimal array (character by character)
for ($i = 0; $i < strlen($encrypted); $i++) {
$char = substr($encrypted, $i, 1);
$val = hexdec($char);
$passbytes[] = $val;
}
// Get length and shift
$length = self::decNextChar($passbytes)['val'];
$shift = self::decNextChar($passbytes)['val'];
// Skip shift bytes
for ($i = 0; $i < $shift; $i++) {
self::decNextChar($passbytes);
}
// Decrypt the actual data
$clearpass = "";
for ($i = 0; $i < $length; $i++) {
$result = self::decNextChar($passbytes);
$clearpass .= chr($result['val']);
$passbytes = $result['passbytes'];
}
// Remove username+hostname to get just the password
if (strpos($clearpass, $key) === 0) {
$clearpass = substr($clearpass, strlen($key));
}
return $clearpass;
}
}